Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 03ae86c

Browse files
committed
O(nlogk) time and O(n) space using min heap.
1 parent 307633e commit 03ae86c

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""
2+
Given a m * n matrix mat of ones (representing soldiers) and zeros (representing civilians), return the indexes of the k weakest rows in the matrix ordered from the weakest to the strongest.
3+
4+
A row i is weaker than row j, if the number of soldiers in row i is less than the number of soldiers in row j, or they have the same number of soldiers but i is less than j. Soldiers are always stand in the frontier of a row, that is, always ones may appear first and then zeros.
5+
6+
7+
8+
Example 1:
9+
10+
Input: mat =
11+
[[1,1,0,0,0],
12+
[1,1,1,1,0],
13+
[1,0,0,0,0],
14+
[1,1,0,0,0],
15+
[1,1,1,1,1]],
16+
k = 3
17+
Output: [2,0,3]
18+
Explanation:
19+
The number of soldiers for each row is:
20+
row 0 -> 2
21+
row 1 -> 4
22+
row 2 -> 1
23+
row 3 -> 2
24+
row 4 -> 5
25+
Rows ordered from the weakest to the strongest are [2,0,3,1,4]
26+
Example 2:
27+
28+
Input: mat =
29+
[[1,0,0,0],
30+
[1,1,1,1],
31+
[1,0,0,0],
32+
[1,0,0,0]],
33+
k = 2
34+
Output: [0,2]
35+
Explanation:
36+
The number of soldiers for each row is:
37+
row 0 -> 1
38+
row 1 -> 4
39+
row 2 -> 1
40+
row 3 -> 1
41+
Rows ordered from the weakest to the strongest are [0,2,3,1]
42+
43+
44+
Constraints:
45+
46+
m == mat.length
47+
n == mat[i].length
48+
2 <= n, m <= 100
49+
1 <= k <= m
50+
matrix[i][j] is either 0 or 1.
51+
"""
52+
class Solution:
53+
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
54+
min_heap,result = [],[]
55+
heapq.heapify(min_heap)
56+
for i,row in enumerate(mat):
57+
heapq.heappush(min_heap,(sum(row),i,row))
58+
if k <= len(min_heap):
59+
while k:
60+
temp = heapq.heappop(min_heap)
61+
result.append(temp[1])
62+
k -= 1
63+
else:
64+
while min_heap:
65+
temp = heapq.heappop(min_heap)
66+
result.append(temp[1])
67+
return result

0 commit comments

Comments
 (0)