zoukankan      html  css  js  c++  java
  • [LeetCode] 554. Brick Wall

    There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks.

    The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right.

    If your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks.

    You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.

    Example:

    Input: [[1,2,2,1],
            [3,1,2],
            [1,3,2],
            [2,4],
            [3,1,2],
            [1,3,1,1]]
    Output: 2
    Explanation: 
    

     Note:

    1. The width sum of bricks in different rows are the same and won't exceed INT_MAX.
    2. The number of bricks in each row is in range [1,10,000]. The height of wall is in range [1,10,000]. Total number of bricks of the wall won't exceed 20,000.

    砖墙。

    你的面前有一堵矩形的、由 n 行砖块组成的砖墙。这些砖块高度相同(也就是一个单位高)但是宽度不同。每一行砖块的宽度之和应该相等。

    你现在要画一条 自顶向下 的、穿过 最少 砖块的垂线。如果你画的线只是从砖块的边缘经过,就不算穿过这块砖。你不能沿着墙的两个垂直边缘之一画线,这样显然是没有穿过一块砖的。

    给你一个二维数组 wall ,该数组包含这堵墙的相关信息。其中,wall[i] 是一个代表从左至右每块砖的宽度的数组。你需要找出怎样画才能使这条线 穿过的砖块数量最少 ,并且返回 穿过的砖块数量 。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/brick-wall
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    题意是你需要对这堵墙画一道垂线,请问如何画,破坏的砖头最少。请返回最少需要破坏几块砖头。一个corner case就是不能从墙的最左边或者最右边画垂线。

    思路是 prefix sum 前缀和。每一行从左往右扫描,记录前缀和。但是记得不要扫描每一行的最后一块砖,因为每一行的砖头的总长度都是一样的。

    时间O(n^2)

    空间O(n)

    Java实现

     1 class Solution {
     2     public int leastBricks(List<List<Integer>> wall) {
     3         // corner case
     4         if (wall == null || wall.size() == 0) {
     5             return 0;
     6         }
     7 
     8         // normal case
     9         int max = 0;
    10         HashMap<Integer, Integer> map = new HashMap<>();
    11         for (int i = 0; i < wall.size(); i++) {
    12             int prefixSum = 0;
    13             for (int j = 0; j < wall.get(i).size() - 1; j++) {
    14                 prefixSum += wall.get(i).get(j);
    15                 map.put(prefixSum, map.getOrDefault(prefixSum, 0) + 1);
    16                 max = Math.max(max, map.get(prefixSum));
    17             }
    18         }
    19         return wall.size() - max;
    20     }
    21 }

    LeetCode 题目总结

  • 相关阅读:
    华为内部面试题库(20)
    华为内部面试题库(18)
    华为内部面试题库(14)
    华为内部面试题库(12)
    华为内部面试题库(16)
    华为内部面试题库(17)
    华为内部面试题库(11)
    华为内部面试题库(13)
    Windows 危险的注册表键
    逆向工程师要学什么?
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13501787.html
Copyright © 2011-2022 走看看