Python | Leetcode Python题解之第378题有序矩阵中第K小的元素

题目:

Python | Leetcode Python题解之第378题有序矩阵中第K小的元素_第1张图片

题解:

class Solution:
    def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
        n = len(matrix)

        def check(mid):
            i, j = n - 1, 0
            num = 0
            while i >= 0 and j < n:
                if matrix[i][j] <= mid:
                    num += i + 1
                    j += 1
                else:
                    i -= 1
            return num >= k

        left, right = matrix[0][0], matrix[-1][-1]
        while left < right:
            mid = (left + right) // 2
            if check(mid):
                right = mid
            else:
                left = mid + 1
        
        return left

你可能感兴趣的:(分享,Python,Leetcode,题解)