1 class Solution:
 2     def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
 3         matrix = [[0 for _ in range(m)]for _ in range(n)]
 4         row,column = [0] * n,[0] * m
 5         for ri in range(len(indices)):
 6             row[indices[ri][0]] += 1
 7             column[indices[ri][1]] += 1
 8         for r in range(len(row)):
 9             if row[r] > 0:
10                 for j in range(m):
11                     matrix[r][j] += row[r]
12         for c in range(len(column)):
13             if column[c] > 0:
14                 for i in range(n):
15                     matrix[i][c] += column[c]
16         count = 0
17         for i in range(n):
18             for j in range(m):
19                 if matrix[i][j] % 2 == 1:
20                     count += 1
21         return count

这个执行效率偏低,下面进行改进:

 1 class Solution:
 2     def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
 3         matrix = [[0 for _ in range(m)]for _ in range(n)]
 4         row,column = [0] * n,[0] * m
 5         count = 0
 6         for ri in range(len(indices)):
 7             row[indices[ri][0]] += 1
 8             column[indices[ri][1]] += 1
 9         for i in range(n):
10             for j in range(m):
11                 if (row[i] + column[j]) % 2 == 1:
12                     count += 1
13         
14         return count

思路:先计算“行”和“列”分别增加了几次。

然后遍历整个二维数组,计算每个元素加1的次数(对应位置的行加1的次数+对应位置列加1的次数)。

增加后,判断此位置是否为奇数(odd),统计所有奇数的个数存储在count中。最后返回count。

 

posted on 2019-11-11 07:02  Sempron2800+  阅读(207)  评论(0编辑  收藏  举报