use heap/priority q , pop k times, push k times
import heapq
class Solution(object):
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
result,heap=None,[]
heapq.heappush(heap,(matrix[0][0],0,0))
while k>0:
result,i,j=heapq.heappop(heap)
if i==0 and j+1<len(matrix):
heapq.heappush(heap,(matrix[i][j+1],i,j+1))
if i+1<len(matrix):
heapq.heappush(heap,(matrix[i+1][j],i+1,j))
k-=1
return result
378. Kth Smallest Element in a Sorted Matrix
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 根据二分搜索法,获取中间值,然后搜索他是否为第k个值。主要中间值不在矩阵内的情况。这就是 这段语句的作用.
- Given a n x n matrix where each of the rows and columns a...
- Given a n x n matrix where each of the rows and columns a...
- Medium Given a n x n matrix where each of the rows and co...
- Given a n x n matrix where each of the rows and columns a...