leetcode Kth Largest Element in a Stream——要熟悉heapq使用

703. Kth Largest Element in a Stream

Easy

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.

Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.

Example:

int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3);   // returns 4
kthLargest.add(5);   // returns 5
kthLargest.add(10);  // returns 5
kthLargest.add(9);   // returns 8
kthLargest.add(4);   // returns 8

Note:

You may assume that nums‘ length ≥ k-1 and k ≥ 1.

"""
 1 import heapq
 2 def heapsort(iterable):
 3     h = []
 4     for i in iterable:
 5         heapq.heappush(h, i)
 6     return [heapq.heappop(h) for i in range(len(h))]
 7
 8 # method 1: sort to list
 9 s = [3, 5, 1, 2, 4, 6, 0, 1]
10 print(heapsort(s))
11 ‘‘‘
12 [0, 1, 1, 2, 3, 4, 5, 6]
13 ‘‘‘
"""
import heapq

class KthLargest(object):

    def __init__(self, k, nums):
        """
        :type k: int
        :type nums: List[int]
        """
        self.arr = []
        self.k = k
        for i in nums:
            if len(self.arr) < self.k:
                heapq.heappush(self.arr, i)
            else:
                if i > self.arr[0]:
                #if heapq.nsmallest(1, self.arr)[0] < i:
                    heapq.heapreplace(self.arr, i)
                    #heapq.heappop(self.arr)
                    #heapq.heappush(self.arr, i)

    def add(self, val):
        """
        :type val: int
        :rtype: int
        """
        if len(self.arr) < self.k:
            heapq.heappush(self.arr, val)
        else:
            if val > self.arr[0]:
            #if heapq.nsmallest(1, self.arr)[0] < val:
                heapq.heapreplace(self.arr, val)
                #heapq.heappop(self.arr)
                #heapq.heappush(self.arr, val)
        assert len(self.arr) == self.k
        return self.arr[0]
        #return heapq.nsmallest(1, self.arr)[0]

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

注意:如果使用heapq.nsmallest(1, self.arr)[0]来返回heap的最小值会有超时问题。

原文地址:https://www.cnblogs.com/bonelee/p/10090580.html

时间: 2024-11-08 22:49:46

leetcode Kth Largest Element in a Stream——要熟悉heapq使用的相关文章

LeetCode 703. Kth Largest Element in a Stream

原题链接在这里:https://leetcode.com/problems/kth-largest-element-in-a-stream/description/ 题目: 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. Your KthLarg

leetcode 703. Kth Largest Element in a Stream &amp; c++ priority_queue &amp; minHeap/maxHeap

703. Kth Largest Element in a Stream & c++ priority_queue & minHeap/maxHeap 相关链接 leetcode c++ priority_queue cplusplus c++ priority_queue cnblog 背景知识 ??堆是算法中常用的数据结构之一,其结构是完全二叉树,但实现的方法最常见的是使用数组:这里主要介绍小顶堆,其根元素最小,对于任何一个节点来说,他都比其后代要小:访问器根元素的时间为O(1):树的

Kth Largest Element in a Stream

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. Your KthLargest class will have a constructor which accepts an integer k and an integer array nums,

leetcode Kth Largest Element in an Array

题目连接 https://leetcode.com/problems/kth-largest-element-in-an-array/ Kth Largest Element in an Array Description Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct eleme

[LeetCode] Kth Largest Element in an Array 数组中第k大的数字

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. For example, Given [3,2,1,5,6,4] and k = 2, return 5. Note: You may assume k is always valid, 1 ≤ k ≤ array'

LeetCode——Kth Largest Element in an Array

Description: Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. For example, Given [3,2,1,5,6,4] and k = 2, return 5. 你确定你不是在逗我? public class Solution { public

LeetCode:Kth Largest Element in an Array(need update)

problem: Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. For example, Given [3,2,1,5,6,4] and k = 2, return 5. Note: You may assume k is always valid, 1 ≤ k

LeetCode算法题-Kth Largest Element in a Stream(Java实现)

这是悦乐书的第296次更新,第315篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第164题(顺位题号是703).设计一个类来查找流中第k个最大元素.请注意,它是排序顺序中的第k个最大元素,而不是第k个不同元素.KthLargest类有一个构造方法,此构造方法有一个整数k和一个整数数组nums两个参数,它包含来自流的初始元素.对于方法KthLargest.add的每次调用,返回表示流中第k个最大元素的元素.例如: int k = 3; int [] arr = [4

Leetcode 703题数据流中的第K大元素(Kth Largest Element in a Stream)Java语言求解

题目链接 https://leetcode-cn.com/problems/kth-largest-element-in-a-stream/ 题目内容 设计一个找到数据流中第K大元素的类(class).注意是排序后的第K大元素,不是第K个不同的元素.你的 KthLargest 类需要一个同时接收整数 k 和整数数组nums 的构造器,它包含数据流中的初始元素.每次调用 KthLargest.add,返回当前数据流中第K大的元素. 示例: int k = 3; int[] arr = [4,5,8