Create k_element_stream.py

This commit is contained in:
marina 2023-08-02 13:56:52 -07:00 committed by GitHub
parent 3eb6a7c828
commit d6fedcee53
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

27
heaps/k_element_stream.py Normal file
View File

@ -0,0 +1,27 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: bt3gl
class KthLargest:
def __init__(self, k, nums):
self.k = k
self.heap = nums
heapq.heapify(self.heap)
while 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]