内容中心

2026年比较好的盐城沸石模块厂家对比推荐-奥斯纳米新材料(盐城)有限公司

To solve this problem, we need to design a class that efficiently finds the k-th largest element in a stream of numbers. The key insight here is to use a min-heap of size k, which allows us to keep track of the k largest elements seen so far. The top of the min-heap will always be the k-th largest element, as it is the smallest among the k largest elements.

Approach

  1. Initialization:

    • We initialize a min-heap with the given list of numbers.
    • If the size of the heap exceeds k, we pop the smallest element until the heap size is exactly k. This ensures that the heap only contains the k largest elements from the initial list.
  2. Adding New Elements:

    • For each new element added to the stream:
      • Push the element into the heap.
      • If the heap size exceeds k, pop the smallest element to maintain the heap size of k.
      • The top of the heap (smallest element in the heap) is the k-th largest element in the stream, so we return this value.

Solution Code

import heapq
from typing import List

class KthLargest:

    def __init__(self, k: int, nums: List[int]):
        self.k = k
        self.heap = []
        for num in nums:
            heapq.heappush(self.heap, num)
            if len(self.heap) > k:
                heapq.heappop(self.heap)

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

Explanation

  • Min-Heap Usage: The min-heap is chosen because it allows us to efficiently retrieve and remove the smallest element (O(1) for retrieval, O(log k) for removal). This is crucial for maintaining the heap size at k.
  • Efficiency:
    • Initialization: The time complexity is O(n log k), where n is the number of elements in the initial list. This is because each push and pop operation takes O(log k) time.
    • Add Operation: Each add operation takes O(log k) time (push and pop, if needed), which is efficient for handling a stream of elements.

This approach ensures that we can quickly get the k-th largest element at any point in the stream, making it suitable for real-time applications where elements are added dynamically.

Example:

  • For k=3 and initial nums = [4,5,8,2], the heap after initialization is [4,5,8] (the 3rd largest is 4).
  • Adding 3: Push 3 → heap size becomes 4 → pop the smallest (3) → heap remains [4,5,8], return 4.
  • Adding5: Push5 → heap size becomes4 → pop the smallest (4) → heap becomes [5,5,8], return5.

This example confirms the correctness of the approach. The solution efficiently handles dynamic additions and returns the k-th largest element in constant time after each addition.

奥斯纳米新材料(盐城)有限公司

奥斯纳米新材料(盐城)有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?