2021-02-11

本文介绍了如何使用堆排序算法解决LeetCode中的kth最大元素问题。通过建立最大堆并维护堆的大小为k,可以高效地在流中找到第k大的元素。博主分享了详细的思路、代码实现以及对堆排序的理解,并提醒读者堆数据结构在面试中的重要性,建议加强学习和练习。
摘要由CSDN通过智能技术生成

2021-02-11 Leetcode每日刷题

题目

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Implement KthLargest class:

  • KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
  • int add(int val) Returns the element representing the kth largest element in the stream.

Example 1:

Input
[“KthLargest”, “add”, “add”, “add”, “add”, “add”]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
Output
[null, 4, 5, 5, 8, 8]

Explanation
KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
kthLargest.add(3); // return 4
kthLargest.add(5); // return 5
kthLargest.add(10); // return 5
kthLargest.add(9); // return 8
kthLargest.add(4); // return 8

Constraints:
1 <= k <= 104
0 <= nums.length <= 104
-104 <= nums[i] <= 104
-104 <= val <= 104
At most 104 calls will be made to add. It is guaranteed that there will be at least k elements in the array when you search for the kth element.

我的思路
没有思路。每次insert之后排序并输出第k个数字可以,但是会超时。不过可以手动排序,初始化后进行排序,接下来每次add使用insert排到合适的位置,但是还是太麻烦了。

参考思路
使用堆排序。之前并没有学过堆排序。可以参考这位的博客写的很详细。
https://www.cnblogs.com/wangchaowei/p/8288216.html
总之,使用heap每次插入一个元素需要从下到上从子节点到根节点排一遍序,每次删除一个元素需要从上到下从根节点到子节点排一遍。如果max-heap(min-heap)的长度为k,那么根节点就是heap中第k小(大)的数字。

那么这道题就可以先把整个数组变成小根堆,并保留前k个元素。每次add时进行heappush()和heappop(),两个操作时间复杂度均为log(k)。

代码:

class KthLargest:

    def __init__(self, k: int, nums: List[int]):
        self.k = k
        self.nums = nums
        heapq.heapify(self.nums)
        while len(self.nums)>self.k:
            heapq.heappop(self.nums)

    def add(self, val: int) -> int:
        heapq.heappush(self.nums,val)
        while len(self.nums) > self.k:
            heapq.heappop(self.nums)
        return self.nums[0]



# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)

提交结果
在这里插入图片描述
总结一下,堆的数据结构要好好学习,经常复习。前K个元素也在面试题中经常出现,需要再多找几道题巩固一下。对这道题本身来说,自己编写几种排序方法也是ok的,可以多写几遍当作复习不同的排序方法了。
最后祝所有人除夕快乐!!!我要去继续写作业了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值