Kth Smallest Element in a Sorted Matrix

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.

Solution

@wangyang:1600ms silly but straight method
class Solution(object):
    def kthSmallest(self, matrix, k):
        """
        :type matrix: List[List[int]]
        :type k: int
        :rtype: int
        """
        n = len(matrix)
        a = matrix[0]
        for i in range(1,n):
            count = 0
            for j in range(n):
                if matrix[i][j]>a[-1]:
                    a.append(matrix[i][j])
                    count = len(a)-1
                    continue
                while matrix[i][j]>a[count]:
                    count+= 1
                a.insert(count,matrix[i][j])
        return a[k-1]

改进思路,只需比较当前行其余元素与第一列元素/二分法

猜你喜欢

转载自blog.csdn.net/byr_wy/article/details/84111737