-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy paththe-k-weakest-rows-in-a-matrix.py
More file actions
32 lines (22 loc) · 1005 Bytes
/
the-k-weakest-rows-in-a-matrix.py
File metadata and controls
32 lines (22 loc) · 1005 Bytes
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
from typing import List, Tuple
class Solution:
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
def k_select(array: List[Tuple[int, int]], k: int) -> List[Tuple[int, int]]:
left, right = 0, len(array) - 1
selected = 0
while selected != k:
pivot = array[right]
selected = left
for pos in range(left, right + 1):
if array[pos] <= pivot:
array[selected], array[pos] = array[pos], array[selected]
selected += 1
if selected > k:
right = selected - 2
selected = 0
elif selected < k:
left = selected
return array[:k]
array = list(map(lambda x: (x[1], x[0]), enumerate(map(sum, mat))))
k_array = k_select(array, k)
return list(map(lambda x: x[1], sorted(k_array, key=lambda x: (x[0], x[1]))))