Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit3adf66b

Browse files
authored
Refactored The K Weakest Rows in a Matrix.java
1 parent121ca50 commit3adf66b

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
classSolution {
22
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]));
45
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])});
67
}
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];
2211
}
23-
returnans;
12+
returnresult;
2413
}
25-
26-
privateintgetLastIndex(int[]arr,intstart,intend) {
27-
intidx = -1;
14+
15+
privateintgetNumberOfOnes(int[]arr) {
16+
intstart =0;
17+
intend =arr.length -1;
2818
while (start <=end) {
2919
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) {
3521
end =mid -1;
22+
}else {
23+
start =mid +1;
3624
}
3725
}
38-
returnidx;
26+
returnend <0 ?0 :start;
3927
}
4028
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp