给你一个 m * n
的矩阵,矩阵中的数字 各不相同 。请你按 任意 顺序返回矩阵中的所有幸运数。
幸运数是指矩阵中满足同时下列两个条件的元素:
- 在同一行的所有元素中最小
- 在同一列的所有元素中最大
解:
1.求出每行最小元素rowmin和每列最大元素colmax
然后遍历matrix,如果同时满足rowmin和colmax,则是幸运数。
class Solution: def luckyNumbers (self, matrix: List[List[int]]) -> List[int]: rows,cols = len(matrix), len(matrix[0]) rowmin = [matrix[i][0] for i in range(rows)] colmax = [matrix[0][j] for j in range(cols)] for i in range(rows): for j in range(cols): x = matrix[i][j] if x < rowmin[i] : rowmin[i] = x if x > colmax[j]: colmax[j] = x #print(rowmin, colmax) return [matrix[i][j] for i in range(rows) for j in range(cols) if matrix[i][j]==rowmin[i] and matrix[i][j] == colmax[j]]
2.对1的改进,最后不需要遍历matrix,因为matrix中元素各不相同,只要求rowmin和colmax交集即可。
class Solution: def luckyNumbers (self, matrix: List[List[int]]) -> List[int]: rows,cols = len(matrix), len(matrix[0]) rowmin = [matrix[i][0] for i in range(rows)] colmax = [matrix[0][j] for j in range(cols)] for i in range(rows): for j in range(cols): x = matrix[i][j] if x < rowmin[i] : rowmin[i] = x if x > colmax[j]: colmax[j] = x #print(rowmin, colmax) return [x for x in rowmin if x in colmax ]
3.评论区的简单写法。
rowmin = [min(i) for i in matrix] colmax = [max(i) for i in zip(*matrix)] return [i for i in rowmin if i in colmax]
zip(*iterables, strict=False)在多个迭代器上并行迭代,从每个迭代器返回一个数据项组成元组。
“不妨换一种方式认识 zip() :它会把行变成列,把列变成行。这类似于 矩阵转置 ”
*在这里是列表解包操作。
使用zip 和* 可实现拆解列表。
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> list(zip(x, y))
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
矩阵转置:martrix是一个二维矩阵,如下操作可以得到它的转置。
list(zip(*matrix))
4. 其他流程控制工具 — Python 3.10.2 文档
解包:
用 *
操作符把实参从列表或元组解包出来
list(range(3, 6)) # normal call with separate arguments
args = [3, 6]
list(range(*args)) # call with arguments unpacked from a
list*args 将列表[3, 6] 解包为单独的参数 3 和6
#如果args = [[1,2],[3,4]] 这样的嵌套列表,*args会解包成[1,2] 和[3,4] 也就是解一层。
**字典解包,将字典解为关键字参数。
def parrot(voltage, state='a stiff', action='voom'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.", end=' ')
print("E's", state, "!")
d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !