2021-02-11

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)

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

你可能感兴趣的:(leetcode)