Skip to content

Commit bf45d70

Browse files
kth smallest element in a sorted matrix
1 parent 08e741e commit bf45d70

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package medium;
2+
3+
import java.util.ArrayList;
4+
import java.util.Collections;
5+
import java.util.List;
6+
/**378. Kth Smallest Element in a Sorted Matrix QuestionEditorial Solution My Submissions
7+
Total Accepted: 5
8+
Total Submissions: 7
9+
Difficulty: Medium
10+
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
11+
12+
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
13+
14+
Example:
15+
16+
matrix = [
17+
[ 1, 5, 9],
18+
[10, 11, 13],
19+
[12, 13, 15]
20+
],
21+
k = 8,
22+
23+
return 13.
24+
Note:
25+
You may assume k is always valid, 1 ≤ k ≤ n2.*/
26+
public class KthSmallestElementInASortedMatrix {
27+
//brute force made it AC'ed, extreme test case needed for OJ
28+
public int kthSmallest(int[][] matrix, int k) {
29+
List<Integer> list = new ArrayList<Integer>();
30+
int n = matrix.length;
31+
for(int i = 0; i < n; i++){
32+
for(int j = 0; j < n; j++){
33+
list.add(matrix[i][j]);
34+
}
35+
}
36+
Collections.sort(list);
37+
return list.get(k-1);
38+
}
39+
40+
//TODO: use heap and binary search to do it.
41+
}

0 commit comments

Comments
 (0)