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:
问题:把一堵墙劈成两半,要求劈开的砖最少。
第一种方案:最直接的想法,从一段开始一刀一刀劈,统计每刀劈开的砖头,返回最小值。
缺点很明显:耗时特别长。Runtime: 1076 ms,而且代码看起来也不少。。。
1 class Solution { 2 public: 3 int leastBricks(vector<vector<int>>& wall) { 4 int res = wall.size(); 5 if (res==0) 6 return 0; 7 int sum = 0; 8 for (auto num: wall[0]) 9 sum += num; 10 int cnt = res; 11 while (sum>0) { 12 res = min(res, cnt); 13 cnt = 0; 14 int brk = INT_MAX; 15 for (int i=0; i<wall.size(); ++i) { 16 brk = min(wall[i].front(), brk); 17 } 18 for (int i=0; i<wall.size(); ++i) { 19 if (wall[i].front() > brk) { 20 wall[i].front() -= brk; 21 ++cnt; 22 } 23 else 24 wall[i].erase(wall[i].begin()); 25 26 } 27 sum -= brk; 28 } 29 return res; 30 31 } 32 };
第二种方案:倒过来想,劈开的砖最少,表示这一刀下去,砖缝最多,所以直接统计砖缝就可以了。可以建一个哈希表来储存每个位置的砖缝数量。
Runtime: 39 ms,而且代码看起来也简洁了很多。
1 class Solution { 2 public: 3 int leastBricks(vector<vector<int>>& wall) { 4 int res = wall.size(); 5 unordered_map<int, int> m; 6 int brk = 0; 7 for (int i=0; i<wall.size(); ++i) { 8 int cnt = 0; 9 for (int j=0; j<wall[i].size()-1; ++j) { 10 cnt += wall[i][j]; 11 ++m[cnt]; 12 brk = max(brk, m[cnt]); 13 } 14 } 15 16 return res-brk; 17 18 } 19 };