leetcode 378. Kth Smallest Element in a Sorted Matrix

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.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

Example:


matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,

return 13.

Note:
You may assume k is always valid, 1 ≤ k ≤ n2.

  • simple solution
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
slist = []
for row in matrix:
slist.extend(row)
slist.sort()
return slist[k-1]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#binary search
class Solution:
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
m, n = len(matrix), len(matrix[0])
left, right = matrix[0][0], matrix[m-1][n-1]
while left < right:
mid = left+(right-left)//2
cnt = 0
j = n-1
for i in range(m):
while j >= 0 and matrix[i][j] > mid:
j -= 1
cnt += (j+1)
if cnt < k: left = mid+1
else: right = mid
return left