Leetcode--Heap

215. Kth Largest Element in an Array

要找第K大的数,就是找第len(nums)-k-1小的数,构造一个最小堆,将前边len(nums)-k小的数都pop出去,堆顶就成了第len(nums)-k-1小的数。
算法复杂度:O(n+(n-k)log(n))
更多解法参考:
https://discuss.leetcode.com/topic/22159/python-different-solutions-with-comments-bubble-sort-selection-sort-heap-sort-and-quick-sort

347. Top K Frequent Elements

use heap sort, we only keep k elements in heap, the k elements are the top k frequent elements
first we count the frequency of each element, then we pick the top frequent elements and put them into heap, we only keep the heap length as k, so it must be the top k frequent elements.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容