-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy path1337-the-k-weakest-rows-in-a-matrix.py
49 lines (40 loc) · 1.18 KB
/
1337-the-k-weakest-rows-in-a-matrix.py
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
49
# time complexity: O(nlogn)
# space complexity: O(k)
from heapq import heappop, heappush
from typing import List
class Solution:
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
def binarySearch(nums: List[int]):
left = 0
right = len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == 1:
left = mid + 1
else:
right = mid - 1
return left
minHeap = []
for r in range(len(mat)):
heappush(minHeap, (binarySearch(mat[r]), r))
result = []
for _ in range(k):
_, currNum = heappop(minHeap)
result.append(currNum)
return result
mat = [[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]]
k = 3
print(Solution().kWeakestRows(mat, k))
mat = [[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]
k = 1
print(Solution().kWeakestRows(mat, k))
mat = [[1, 0, 0, 0],
[1, 1, 1, 1],
[1, 0, 0, 0],
[1, 0, 0, 0]]
k = 2
print(Solution().kWeakestRows(mat, k))