[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 leastbricks.

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.

 

這道題給了我們一個磚頭牆壁,上面由不同的長度的磚頭組成,讓選個地方從上往下把牆劈開,使得被劈開的磚頭個數最少,前提是不能從牆壁的兩邊劈,這樣沒有什么意義。這里使用一個 HashMap 來建立每一個斷點的長度和其出現頻率之間的映射,這樣只要從斷點頻率出現最多的地方劈牆,損壞的板磚一定最少。遍歷磚牆的每一層,新建一個變量 sum,然后從第一塊轉頭遍歷到倒數第二塊,將當前轉頭長度累加到 sum 上,這樣每次得到的 sum 就是斷點的長度,將其在 HashMap 中的映射值自增1,並且每次都更新下最大的映射值到變量 mx,這樣最終 mx 就是出現次數最多的斷點值,在這里劈開,絕對損傷的轉頭數量最少,參見代碼如下:

 

class Solution {
public:
    int leastBricks(vector<vector<int>>& wall) {
        int mx = 0, n = wall.size();
        unordered_map<int, int> m;
        for (auto &row : wall) {
            int sum = 0, cnt = row.size();
            for (int i = 0; i < cnt - 1; ++i) {
                sum += row[i];
                ++m[sum];
                mx = max(mx, m[sum]);
            }
        }
        return n - mx;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/554

 

參考資料:

https://leetcode.com/problems/brick-wall/

https://leetcode.com/problems/brick-wall/discuss/101738/C%2B%2B-6-lines-(hash-map)

https://leetcode.com/problems/brick-wall/discuss/101728/I-DON'T-THINK-THERE-IS-A-BETTER-PERSON-THAN-ME-TO-ANSWER-THIS-QUESTION

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM