Skip to content

Commit 30c2d0b

Browse files
committed
554.Brick Wall (python)
1 parent a58c7bb commit 30c2d0b

File tree

3 files changed

+76
-0
lines changed

3 files changed

+76
-0
lines changed

img/brick_wall.png

44.5 KB
Loading

solution/0554.Brick Wall/README.md

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
## 砖墙
2+
3+
### 问题描述
4+
5+
你的面前有一堵方形的、由多行砖块组成的砖墙。 这些砖块高度相同但是宽度不同。你现在要画一条自顶向下的、穿过最少砖块的垂线。
6+
7+
砖墙由行的列表表示。 每一行都是一个代表从左至右每块砖的宽度的整数列表。
8+
9+
如果你画的线只是从砖块的边缘经过,就不算穿过这块砖。你需要找出怎样画才能使这条线穿过的砖块数量最少,并且返回穿过的砖块数量。
10+
11+
你不能沿着墙的两个垂直边缘之一画线,这样显然是没有穿过一块砖的。
12+
13+
**示例1:**
14+
```
15+
输入: [[1,2,2,1],
16+
[3,1,2],
17+
[1,3,2],
18+
[2,4],
19+
[3,1,2],
20+
[1,3,1,1]]
21+
22+
输出: 2
23+
```
24+
25+
![示例1](/img/brick_wall.png)
26+
27+
**提示:**
28+
- 每一行砖块的宽度之和应该相等,并且不能超过 `INT_MAX`
29+
- 每一行砖块的数量在 [1,10,000] 范围内, 墙的高度在 [1,10,000] 范围内, 总的砖块数量不超过 20,000。
30+
31+
### 解法
32+
33+
记录每个长度(每个砖块右侧到最左侧的长度)出现的次数, 总层数减去出现次数最多的长度, 就是最少交叉的数量。每层最后一块砖的右侧是边缘,不考虑。
34+
35+
```python
36+
class Solution:
37+
def leastBricks(self, wall):
38+
dic = {}
39+
count = 0
40+
for hang in wall:
41+
count = 0
42+
for j, ele in enumerate(hang):
43+
if j == len(hang) - 1:
44+
break
45+
count += ele
46+
if count not in dic:
47+
dic[count] = 1
48+
else:
49+
dic[count] += 1
50+
51+
if not dic:
52+
return len(wall)
53+
return len(wall) - dic[max(dic, key=dic.get)]
54+
```

solution/0554.Brick Wall/Solution.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution:
2+
def leastBricks(self, wall):
3+
"""
4+
:type wall: List[List[int]]
5+
:rtype: int
6+
"""
7+
dic = {}
8+
count = 0
9+
for hang in wall:
10+
count = 0
11+
for j, ele in enumerate(hang):
12+
if j == len(hang) - 1:
13+
break
14+
count += ele
15+
if count not in dic:
16+
dic[count] = 1
17+
else:
18+
dic[count] += 1
19+
20+
if not dic:
21+
return len(wall)
22+
return len(wall) - dic[max(dic, key=dic.get)]

0 commit comments

Comments
 (0)