1337. 矩阵中战斗力最弱的 K 行
为保证权益,题目请参考 1337. 矩阵中战斗力最弱的 K 行(From LeetCode).
解决方案1
Python
python
# 1337. 矩阵中战斗力最弱的 K 行
# https://leetcode-cn.com/problems/the-k-weakest-rows-in-a-matrix/
from typing import List
import functools
class Solution:
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
dp = []
for i in range(len(mat)):
t = 0
for j in range(len(mat[0])):
if mat[i][j] == 1:
t += 1
else:
break
dp.append((t, i))
def ccc(a, b):
if a[0] == b[0]:
return a[1] - b[1]
else:
return a[0] - b[0]
dp.sort(key=functools.cmp_to_key(ccc))
# print(dp)
ans = []
for i in range(k):
ans.append(dp[i][1])
return ans
if __name__ == "__main__":
solution = Solution()
print(
solution.kWeakestRows(
[
[1, 1, 0, 0, 0],
[1, 1, 1, 1, 0],
[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 1, 1, 1, 1],
],
3,
)
)
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
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