Thereis a brick wall in front of you. The wall is rectangular and has several rowsof bricks. The bricks have the same height but different width. You want todraw a vertical line from the top to the bottom and cross the least bricks.
Thebrick wall is represented by a list of rows. Each row is a list of integersrepresenting the width of each brick in this row from left to right.
Ifyour line go through the edge of a brick, then the brick is not considered ascrossed. You need to find out how to draw the line to cross the least bricksand return the number of crossed bricks.
Youcannot draw a line just along one of the two vertical edges of the wall, inwhich 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 differentrows are the same and won't exceed INT_MAX.
2. The number of bricks in each row isin range [1,10,000]. The height of wall is in range [1,10,000]. Total number ofbricks of the wall won't exceed 20,000.
这题说简单也简单,一般人想的方法大概就是建立一个数组,存储任何一个位置的裂缝的数量,但是这一题不需要这么复杂,直接使用一个map,map[i]存储位置i的裂缝的数量,在算法的最后取裂缝最多的那一列就好了,使用height减去裂缝最多的那一列就能得到正确的结果,这里需要注意裂缝最多的那一列的裂缝数量要初始化为0,这样当不存在裂缝的时候能够正确的返回墙的高度,
还有就是这一题的map不需要排序,使用unordered_map能提升算法的速度,一定要记住!,unordered_set也是存在的,不过set不是一般都没有排序的吗?
class Solution {
public:
int leastBricks(vector<vector<int>>& wall) {
map<int, int> mark;
for (int i = 0; i < wall.size(); i++)
{
int tmp = 0;
for (int j = 0; j < wall[i].size() - 1; j++)
{
mark[(tmp += wall[i][j])] += 1;
}
}
int theMax = 0;
for (auto u : mark)
{
theMax = max(u.second, theMax);
}
return wall.size() - theMax;
}
};