leetcode 378. Kth Smallest Element in a Sorted Matrix
2016-12-07 22:30
561 查看
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:
Note:
You may assume k is always valid, 1 ≤ k ≤ n2.
骚年,牢记最小堆的实现!
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.
Note:
You may assume k is always valid, 1 ≤ k ≤ n2.
#! /usr/bin/evn python #coding:utf-8 from heapq import heappush, heappop class MinQ(object): def __init__(self): self.h = [] def push(self, value): heappush(self.h, value) def pop(self): return heappop(self.h) class Solution(object): def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ assert matrix rows_cnt = len(matrix) min_q = MinQ() for j,c in enumerate(matrix[0]): min_q.push([c, 0, j]) n = 1 val = None while n <= k: val = min_q.pop() i,j = val[1]+1, val[2] if i < rows_cnt: min_q.push([matrix[i][j], i, j]) n += 1 return val[0]
骚年,牢记最小堆的实现!
相关文章推荐
- 梁勇2011JAVA语言程序设计基础篇第16章编程题16.11
- CodeForces 141C Queue
- 总结68
- 使用maven的profile切换项目各环境的参数
- 使用MyBatis 框架犯的错误
- 在职研一英语选词填空及划线词替换习题及答案
- 使用MyBatis 框架犯的错误
- 三种 三栏网页宽度自适应布局方法
- DotNet二维码操作组件ThoughtWorks.QRCode
- 常量指针和指针常量
- 无需焦点的跑马灯TextView
- Linux
- 在C语言中,如何做到在用户输入密码时不显示密码本身,只回显星号。或者什么都不显示?
- Oracle 物化视图之--复杂物化视图创建
- Laravel5.03开发环境搭建
- java多线程-06-atomic包
- 系统编程中的文件大小修改truncate/lseek
- 金牌 银牌 铜牌
- gcc、gdb学习笔记
- JavaSrcipt中的call()和apply()方法理解