|
1 | 1 | classSolution {
|
2 | 2 | publicint[]kWeakestRows(int[][]mat,intk) {
|
3 |
| -Map<Integer,Integer>map =newHashMap<>(); |
| 3 | +PriorityQueue<int[]>pq =newPriorityQueue<>( |
| 4 | +Comparator.comparingInt((int[]o) ->o[1]).thenComparingInt(o ->o[0])); |
4 | 5 | for (inti =0;i <mat.length;i++) {
|
5 |
| -map.put(i,getLastIndex(mat[i],0,mat[i].length -1) +1); |
| 6 | +pq.add(newint[]{i,getNumberOfOnes(mat[i])}); |
6 | 7 | }
|
7 |
| -PriorityQueue<Integer>pq =newPriorityQueue<Integer>(newComparator<Integer>(){ |
8 |
| -publicintcompare(Integero1,Integero2) { |
9 |
| -intc =map.get(o1) -map.get(o2); |
10 |
| -if (c !=0) { |
11 |
| -returnc; |
12 |
| - } |
13 |
| -returno1 -o2; |
14 |
| - } |
15 |
| - }); |
16 |
| -for (inti =0;i <mat.length;i++) { |
17 |
| -pq.add(i); |
18 |
| - } |
19 |
| -int[]ans =newint[k]; |
20 |
| -for (inti =0;i <k;i++) { |
21 |
| -ans[i] =pq.poll(); |
| 8 | +int[]result =newint[k]; |
| 9 | +for (inti =0;i <result.length && !pq.isEmpty();i++) { |
| 10 | +result[i] =pq.poll()[0]; |
22 | 11 | }
|
23 |
| -returnans; |
| 12 | +returnresult; |
24 | 13 | }
|
25 |
| - |
26 |
| -privateintgetLastIndex(int[]arr,intstart,intend) { |
27 |
| -intidx = -1; |
| 14 | + |
| 15 | +privateintgetNumberOfOnes(int[]arr) { |
| 16 | +intstart =0; |
| 17 | +intend =arr.length -1; |
28 | 18 | while (start <=end) {
|
29 | 19 | intmid = (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 |
| -returnidx; |
| 26 | +returnend <0 ?0 :start; |
39 | 27 | }
|
40 | 28 | }
|