LeetCode | 554. Brick Wall map技巧题

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;
}
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值