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:

1
2
3
4
5
6
7
8
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.

思路

采用了一个最暴力的方法,把每一行的元素全部添加到一个一维数组里,然后排一下序。结果幸运地没有超时。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
stride = []
for m in matrix:
for i in m:
stride.append(i)
stride.sort()
return stride[k-1]

这道题用二分法更加省时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
high = matrix[-1][-1]
low = matrix[0][0]
mid = 0
if (high == low):
mid = high
count = 0
# 注意要取不等号,而不是小于号;
while( mid != low or low != high ):
mid = ( high + low ) / 2
# 统计小于等于k的元素个数
for numbers in matrix:
for num in numbers:
if (num <= mid):
count += 1
if (count >= k):
high = mid
else:
# 在这个地方需要把低界+1,因为需要有一个Bias
low = mid + 1
count = 0
return mid