Skip to content

Commit 3adf66b

Browse files
authored
Refactored The K Weakest Rows in a Matrix.java
1 parent 121ca50 commit 3adf66b

File tree

1 file changed

+15
-27
lines changed

1 file changed

+15
-27
lines changed
Lines changed: 15 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,28 @@
11
class Solution {
22
public int[] kWeakestRows(int[][] mat, int k) {
3-
Map<Integer, Integer> map = new HashMap<>();
3+
PriorityQueue<int[]> pq = new PriorityQueue<>(
4+
Comparator.comparingInt((int[] o) -> o[1]).thenComparingInt(o -> o[0]));
45
for (int i = 0; i < mat.length; i++) {
5-
map.put(i, getLastIndex(mat[i], 0, mat[i].length - 1) + 1);
6+
pq.add(new int[]{i, getNumberOfOnes(mat[i])});
67
}
7-
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(new Comparator<Integer>(){
8-
public int compare(Integer o1, Integer o2) {
9-
int c = map.get(o1) - map.get(o2);
10-
if (c != 0) {
11-
return c;
12-
}
13-
return o1 - o2;
14-
}
15-
});
16-
for (int i = 0; i < mat.length; i++) {
17-
pq.add(i);
18-
}
19-
int[] ans = new int[k];
20-
for (int i = 0; i < k; i++) {
21-
ans[i] = pq.poll();
8+
int[] result = new int[k];
9+
for (int i = 0; i < result.length && !pq.isEmpty(); i++) {
10+
result[i] = pq.poll()[0];
2211
}
23-
return ans;
12+
return result;
2413
}
25-
26-
private int getLastIndex(int[] arr, int start, int end) {
27-
int idx = -1;
14+
15+
private int getNumberOfOnes(int[] arr) {
16+
int start = 0;
17+
int end = arr.length - 1;
2818
while (start <= end) {
2919
int mid = (start + end) / 2;
30-
if (arr[mid] == 1) {
31-
idx = Math.max(idx, mid);
32-
start = mid + 1;
33-
}
34-
else {
20+
if (arr[mid] == 0) {
3521
end = mid - 1;
22+
} else {
23+
start = mid + 1;
3624
}
3725
}
38-
return idx;
26+
return end < 0 ? 0 : start;
3927
}
4028
}

0 commit comments

Comments
 (0)