Leetcode 3030. Find the Grid of Region Average
- Leetcode 3030. Find the Grid of Region Average
- 1. 解题思路
- 2. 代码实现
- 题目链接:3030. Find the Grid of Region Average
1. 解题思路
这一题我的思路上也没啥巧妙的,就是大力出奇迹,直接就是遍历所有3x3的区间,找到左右的满足条件的region,然后update一下每一个region当中元素的值,最后统一算一次平均就行了。
2. 代码实现
给出python代码实现如下:
class Solution:
def resultGrid(self, image: List[List[int]], threshold: int) -> List[List[int]]:
n, m = len(image), len(image[0])
def avg(arr, default=0):
if len(arr) == 0:
return default
return sum(arr) // len(arr)
def is_region(elems):
for i in range(9):
if i % 3 != 2 and abs(elems[i]-elems[i+1]) > threshold:
return False
if i < 6 and abs(elems[i]-elems[i+3]) > threshold:
return False
return True
regions = defaultdict(list)
for i in range(n-2):
for j in range(m-2):
elems = [image[i+k//3][j+k%3] for k in range(9)]
if is_region(elems):
_avg = avg(elems)
for k in range(9):
regions[(i+k//3, j+k%3)].append(_avg)
results = [[avg(regions[(i, j)], image[i][j]) for j in range(m)] for i in range(n)]
return results
提交代码评测得到:耗时5843ms,占用内存112MB。