Skip to content

Commit 5502fe6

Browse files
authored
Update The K Weakest Rows in a Matrix.java
1 parent b07d068 commit 5502fe6

File tree

1 file changed

+23
-23
lines changed

1 file changed

+23
-23
lines changed
Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,28 @@
11
class Solution {
2-
public int[] kWeakestRows(int[][] mat, int k) {
3-
PriorityQueue<int[]> pq = new PriorityQueue<>(
4-
Comparator.comparingInt((int[] o) -> o[1]).thenComparingInt(o -> o[0]));
5-
for (int i = 0; i < mat.length; i++) {
6-
pq.add(new int[]{i, getNumberOfOnes(mat[i])});
2+
public int[] kWeakestRows(int[][] mat, int k) {
3+
PriorityQueue<int[]> pq =
4+
new PriorityQueue<>(Comparator.comparingInt((int[] o) -> o[1]).thenComparingInt(o -> o[0]));
5+
for (int i = 0; i < mat.length; i++) {
6+
pq.add(new int[]{i, findNumberOfSoldiers(mat[i])});
7+
}
8+
int[] result = new int[k];
9+
for (int i = 0; i < k && !pq.isEmpty(); i++){
10+
result[i] = pq.poll()[0];
11+
}
12+
return result;
713
}
8-
int[] result = new int[k];
9-
for (int i = 0; i < result.length && !pq.isEmpty(); i++) {
10-
result[i] = pq.poll()[0];
11-
}
12-
return result;
13-
}
1414

15-
private int getNumberOfOnes(int[] arr) {
16-
int start = 0;
17-
int end = arr.length - 1;
18-
while (start <= end) {
19-
int mid = (start + end) / 2;
20-
if (arr[mid] == 0) {
21-
end = mid - 1;
22-
} else {
23-
start = mid + 1;
24-
}
15+
private int findNumberOfSoldiers(int[] row) {
16+
int left = 0;
17+
int right = row.length - 1;
18+
while (left <= right) {
19+
int mid = (left + right) / 2;
20+
if (row[mid] == 0) {
21+
right = mid - 1;
22+
} else {
23+
left = mid + 1;
24+
}
25+
}
26+
return right < 0 ? 0 : left;
2527
}
26-
return end < 0 ? 0 : start;
27-
}
2828
}

0 commit comments

Comments
 (0)