-
Notifications
You must be signed in to change notification settings - Fork 278
/
Copy pathTheKWeakestRowsinaMatrix.java
68 lines (57 loc) · 1.46 KB
/
TheKWeakestRowsinaMatrix.java
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
class Solution {
// TC mlogk + mlogn
// SC k
public int[] kWeakestRows(int[][] mat, int k) {
Comparator<int[]> customCompare = new Comparator<int[]>(){
@Override
public int compare(int[] a, int[] b){
if(a[0] == b[0]){
return b[1] - a[1];
} else{
return b[0] - a[0];
}
}
};
// <1s count, row index>
PriorityQueue<int[]> pq = new PriorityQueue<int[]>(customCompare); // k
for(int i=0;i<mat.length;i++){
int[] row = mat[i];
//
int countOnes =getCount(row);
pq.offer(new int[]{countOnes, i});
if(pq.size() > k){
pq.poll();
}
}
int[] ans = new int[k];
int i = k-1;
while(!pq.isEmpty()){
ans[i]= pq.poll()[1];
i--;
}
return ans;
}
private int getCountLinear(int[] row){
int count =0;
for(int el: row){
if(el==1){
count++;
}
}
return count;
}
// log(n)
private int getCount(int[] row){
int low = 0;
int high = row.length;
while(low<high){
int mid = low+ (high -low)/2;
if(row[mid] == 1){
low = mid+1;
} else {
high = mid;
}
}
return low;
}
}