LeetCode-LCP74 最强祝福力场
Table of Contents
LeetCode-LCP74 最强祝福力场 #
Solution 1 #
离散化 + 二维差分数组.
代码如下:
class Solution:
def fieldOfGreatestBlessing(self, forceField: List[List[int]]) -> int:
x_set, y_set = set(), set()
for (x, y, side) in forceField:
x_set.add(2 * x - side)
x_set.add(2 * x + side)
y_set.add(2 * y - side)
y_set.add(2 * y + side)
xs, ys = sorted(x_set), sorted(y_set)
m, n = len(xs), len(ys)
d = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for (x, y, side) in forceField:
i1 = bisect_left(xs, 2 * x - side)
j1 = bisect_left(ys, 2 * y - side)
i2 = bisect_left(xs, 2 * x + side)
j2 = bisect_left(ys, 2 * y + side)
d[i1][j1] += 1
d[i1][j2 + 1] -= 1
d[i2 + 1][j1] -= 1
d[i2 + 1][j2 + 1] += 1
ans = 0
for i in range(m):
for j in range(n):
d[i][j] += (d[i - 1][j] if i > 0 else 0) + (d[i][j - 1] if j > 0 else 0) - (d[i - 1][j - 1] if i > 0 and j > 0 else 0)
ans = max(ans, d[i][j])
return ans