Skip to content

Commit b34fad8

Browse files
committed
modify code
1 parent d14893c commit b34fad8

File tree

1 file changed

+49
-3
lines changed

1 file changed

+49
-3
lines changed

src/topinterviewquestions/Problem_0378_KthSmallestElementInSortedMatrix.java

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,10 @@ public int compare(Node o1, Node o2) {
2727

2828
}
2929

30-
public static int kthSmallest(int[][] matrix, int k) {
30+
public static int kthSmallest1(int[][] matrix, int k) {
3131
int N = matrix.length;
3232
int M = matrix[0].length;
3333
PriorityQueue<Node> heap = new PriorityQueue<>(new NodeComparator());
34-
// i,j set[i][j] = true
35-
// i,j set[i][j] = false
3634
boolean[][] set = new boolean[N][M];
3735
heap.add(new Node(matrix[0][0], 0, 0));
3836
set[0][0] = true;
@@ -57,4 +55,52 @@ public static int kthSmallest(int[][] matrix, int k) {
5755
return ans.value;
5856
}
5957

58+
public static int kthSmallest2(int[][] matrix, int k) {
59+
int N = matrix.length;
60+
int M = matrix[0].length;
61+
int left = matrix[0][0];
62+
int right = matrix[N - 1][M - 1];
63+
int ans = 0;
64+
while (left <= right) {
65+
int mid = left + ((right - left) >> 1);
66+
Info info = noMoreNum(matrix, mid);
67+
if (info.num < k) {
68+
left = mid + 1;
69+
} else {
70+
ans = info.near;
71+
right = mid - 1;
72+
}
73+
}
74+
return ans;
75+
}
76+
77+
public static class Info {
78+
public int near;
79+
public int num;
80+
81+
public Info(int n1, int n2) {
82+
near = n1;
83+
num = n2;
84+
}
85+
}
86+
87+
public static Info noMoreNum(int[][] matrix, int value) {
88+
int near = Integer.MIN_VALUE;
89+
int num = 0;
90+
int N = matrix.length;
91+
int M = matrix[0].length;
92+
int row = 0;
93+
int col = M - 1;
94+
while (row < N && col >= 0) {
95+
if (matrix[row][col] <= value) {
96+
near = Math.max(near, matrix[row][col]);
97+
num += col + 1;
98+
row++;
99+
} else {
100+
col--;
101+
}
102+
}
103+
return new Info(near, num);
104+
}
105+
60106
}

0 commit comments

Comments
 (0)