-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path15. The K Weakest Rows in a Matrix
93 lines (71 loc) · 2.24 KB
/
15. The K Weakest Rows in a Matrix
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
PQ -> int[] --> 0 -> numOfSoldier, 1 -> indexOfRow
maxHeap --> eliminate the maxValues
a,b ---> a[0], b[0] in desc
a[o] == b[0] --> a[1] b[1] in desc
*/
//using Priority Queue
class Solution {
public int[] kWeakestRows(int[][] mat, int k) {
PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> a[0]!=b[0] ? b[0]-a[0] : b[1]-a[1]);
int[] res = new int[k];
for(int i = 0; i < mat.length; i++) {
int soldiers = 0;
for(int j = 0; j < mat[0].length; j++) {
if(mat[i][j] == 1) soldiers++;
else break;
}
pq.offer(new int[]{soldiers, i});
}
while(pq.size() > k){
pq.poll();
}
while(k > 0) res[--k] = pq.poll()[1];
return res;
}
}
//Using Binary Seearch
class Solution {
public int[] kWeakestRows(int[][] mat, int k) {
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] != b[0] ? b[0] - a[0] : b[1] - a[1]);
int[] ans = new int[k];
for (int i = 0; i < mat.length; i++) {
pq.offer(new int[] {numOnes(mat[i]), i});
if (pq.size() > k)
pq.poll();
}
while (k > 0)
ans[--k] = pq.poll()[1];
return ans;
}
private int numOnes(int[] row) {
int lo = 0;
int hi = row.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (row[mid] == 1)
lo = mid + 1;
else
hi = mid;
}
return lo;
}
}
//Using Array
class Solution {
public int[] kWeakestRows(int[][] mat, int k) {
int[] count = new int[mat.length];
int[] res = new int[k];
for(int i = 0; i < mat.length; i++) {
int soldiers = 0;
for(int j = 0; j < mat[0].length; j++) {
if(mat[i][j] == 1) soldiers++;
else break;
}
count[i] = soldiers*1000 + i;
}
Arrays.sort(count);
for(int i =0; i < k; i++) res[i] = count[i]%1000;
return res;
}
}