-
Notifications
You must be signed in to change notification settings - Fork 0
/
1878.矩阵中最大的三个菱形和.py
54 lines (43 loc) · 1.84 KB
/
1878.矩阵中最大的三个菱形和.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Answer:
def __init__(self):
self.ans = [0, 0, 0]
def put(self, x: int):
_ans = self.ans
if x > _ans[0]:
_ans[0], _ans[1], _ans[2] = x, _ans[0], _ans[1]
elif x != _ans[0] and x > _ans[1]:
_ans[1], _ans[2] = x, _ans[1]
elif x != _ans[0] and x != _ans[1] and x > _ans[2]:
_ans[2] = x
def get(self) -> List[int]:
_ans = self.ans
return [num for num in _ans if num != 0]
class Solution:
def getBiggestThree(self, grid: List[List[int]]) -> List[int]:
m, n = len(grid), len(grid[0])
sum1 = [[0] * (n + 2) for _ in range(m + 1)]
sum2 = [[0] * (n + 2) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
sum1[i][j] = sum1[i - 1][j - 1] + grid[i - 1][j - 1]
sum2[i][j] = sum2[i - 1][j + 1] + grid[i - 1][j - 1]
ans = Answer()
for i in range(m):
for j in range(n):
# 单独的一个格子也是菱形
ans.put(grid[i][j])
for k in range(i + 2, m, 2):
ux, uy = i, j
dx, dy = k, j
lx, ly = (i + k) // 2, j - (k - i) // 2
rx, ry = (i + k) // 2, j + (k - i) // 2
if ly < 0 or ry >= n:
break
ans.put(
(sum2[lx + 1][ly + 1] - sum2[ux][uy + 2]) +
(sum1[rx + 1][ry + 1] - sum1[ux][uy]) +
(sum1[dx + 1][dy + 1] - sum1[lx][ly]) +
(sum2[dx + 1][dy + 1] - sum2[rx][ry + 2]) -
(grid[ux][uy] + grid[dx][dy] + grid[lx][ly] + grid[rx][ry])
)
return ans.get()