|
1 | 1 | class Solution {
|
2 | 2 | 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])); |
4 | 5 | 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])}); |
6 | 7 | }
|
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]; |
22 | 11 | }
|
23 |
| - return ans; |
| 12 | + return result; |
24 | 13 | }
|
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; |
28 | 18 | while (start <= end) {
|
29 | 19 | 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) { |
35 | 21 | end = mid - 1;
|
| 22 | + } else { |
| 23 | + start = mid + 1; |
36 | 24 | }
|
37 | 25 | }
|
38 |
| - return idx; |
| 26 | + return end < 0 ? 0 : start; |
39 | 27 | }
|
40 | 28 | }
|
0 commit comments