Open azl397985856 opened 4 months ago
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
n = len(matrix)
h = [(matrix[i][0], i, 0) for i in range(n)]
heapify(h)
while k:
num,x,y = heappop(h)
if y!=n-1:
heappush(h, (matrix[x][y+1], x, y+1))
k -= 1
ans = num
return ans
class Solution {
public:
int kthSmallest(vector<vector
class Solution:
def countLessEqual(self, matrix, mid, smaller, larger):
count, n = 0, len(matrix)
row, col = n - 1, 0
while row >= 0 and col < n:
if matrix[row][col] > mid:
# As matrix[row][col] is bigger than the mid, let's keep track of the
# smallest number greater than the mid
larger = min(larger, matrix[row][col])
row -= 1
else:
# As matrix[row][col] is less than or equal to the mid, let's keep track of the
# biggest number less than or equal to the mid
smaller = max(smaller, matrix[row][col])
count += row + 1
col += 1
return count, smaller, larger
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
n = len(matrix)
start, end = matrix[0][0], matrix[n - 1][n - 1]
while start < end:
mid = start + (end - start) / 2
smaller, larger = (matrix[0][0], matrix[n - 1][n - 1])
count, smaller, larger = self.countLessEqual(matrix, mid, smaller, larger)
if count == k:
return smaller
if count < k:
start = larger # search higher
else:
end = smaller # search lower
return start
378. 有序矩阵中第 K 小的元素
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix/
前置知识
题目描述
示例:
matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8,
返回 13。
提示: 你可以假设 k 的值永远是有效的,1 ≤ k ≤ n2 。