|
1 | 1 | 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; |
7 | 13 | }
|
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 |
| - } |
14 | 14 |
|
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; |
25 | 27 | }
|
26 |
| - return end < 0 ? 0 : start; |
27 |
| - } |
28 | 28 | }
|
0 commit comments