卖萌的弱渣

I am stupid, I am hungry.

K 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:

1
2
3
4
5
6
7
8
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.

Solution

  • 二分查找,start = matrix[0][0], end = matrix[-1][-1]
  • mid = (start+end)/2,统计小于等于mid的个数(统计时,以左下角为起点)
(Kth-Smallest-Element-in-A-Sorted-Matrix.py) download
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
30
31
32
33
34
class Solution(object):
    def kthSmallest(self, matrix, k):
        """
        :type matrix: List[List[int]]
        :type k: int
        :rtype: int
        """
        n = len(matrix)
        l = matrix[0][0]
        r = matrix[n-1][n-1]

        while l <= r:
            mid_val = (l+r)/2
            cnt = self.countLowerNumbers(matrix, mid_val)
            if cnt < k:
                l = mid_val+1
            else:
                r = mid_val-1
        return l

    def countLowerNumbers(self,matrix,mid_val):
        # 从左下角开始统计相等或者小于mid_val的数量
        n = len(matrix)
        i = n-1
        j = 0
        cnt = 0
        while i >=0 and j < n:
            if mid_val >= matrix[i][j]:
                # 整个一列都是小于mid_val
                cnt += i+1
                j += 1
            else:
                i -= 1
        return cnt