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

Commit9e10997

Browse files
refactor 378
1 parent55f4dab commit9e10997

File tree

1 file changed

+21
-20
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+21
-20
lines changed

‎src/main/java/com/fishercoder/solutions/_378.java

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,28 @@ public int kthSmallest(int[][] matrix, int k) {
2323
}
2424
}
2525

26+
2627
publicstaticclassSolution2 {
28+
/**
29+
* use heap data structure
30+
*/
31+
publicintkthSmallest(int[][]matrix,intk) {
32+
PriorityQueue<int[]>heap =newPriorityQueue<>((a,b) ->Integer.compare(a[0],b[0]));
33+
for (inti =0;i <Math.min(matrix.length,k);i++) {
34+
//we store value, rowIndex, colIndex as an array into this heap
35+
heap.offer(newint[]{matrix[i][0],i,0});
36+
}
37+
while (k-- >1) {
38+
int[]min =heap.poll();
39+
if (min[2] +1 <matrix[min[1]].length) {
40+
heap.offer(newint[]{matrix[min[1]][min[2] +1],min[1],min[2] +1});
41+
}
42+
}
43+
returnheap.poll()[0];
44+
}
45+
}
46+
47+
publicstaticclassSolution3 {
2748
/**
2849
* Binary Search : The idea is to pick a mid number, then compare it with the elements in each row, we start form
2950
* end of row util we find the element is less than the mid, the left side element is all less than mid; keep tracking elements
@@ -53,24 +74,4 @@ public int kthSmallest(int[][] matrix, int k) {
5374
returnlo;
5475
}
5576
}
56-
57-
publicstaticclassSolution3 {
58-
/**
59-
* use heap data structure
60-
*/
61-
publicintkthSmallest(int[][]matrix,intk) {
62-
PriorityQueue<int[]>heap =newPriorityQueue<>((a,b) ->a[0] -b[0]);
63-
for (inti =0;i <matrix.length;i++) {
64-
//we store value, rowIndex, colIndex as an array into this heap
65-
heap.offer(newint[]{matrix[i][0],i,0});
66-
}
67-
while (k-- >1) {
68-
int[]min =heap.poll();
69-
if (min[2] +1 <matrix[min[1]].length) {
70-
heap.offer(newint[]{matrix[min[1]][min[2] +1],min[1],min[2] +1});
71-
}
72-
}
73-
returnheap.poll()[0];
74-
}
75-
}
7677
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp