@@ -27,12 +27,10 @@ public int compare(Node o1, Node o2) {
27
27
28
28
}
29
29
30
- public static int kthSmallest (int [][] matrix , int k ) {
30
+ public static int kthSmallest1 (int [][] matrix , int k ) {
31
31
int N = matrix .length ;
32
32
int M = matrix [0 ].length ;
33
33
PriorityQueue <Node > heap = new PriorityQueue <>(new NodeComparator ());
34
- // i,j set[i][j] = true
35
- // i,j set[i][j] = false
36
34
boolean [][] set = new boolean [N ][M ];
37
35
heap .add (new Node (matrix [0 ][0 ], 0 , 0 ));
38
36
set [0 ][0 ] = true ;
@@ -57,4 +55,52 @@ public static int kthSmallest(int[][] matrix, int k) {
57
55
return ans .value ;
58
56
}
59
57
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
+
60
106
}
0 commit comments