mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Create k_element_stream.py
This commit is contained in:
parent
3eb6a7c828
commit
d6fedcee53
27
heaps/k_element_stream.py
Normal file
27
heaps/k_element_stream.py
Normal 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]
|
||||||
|
|
||||||
|
|
||||||
|
|
Loading…
x
Reference in New Issue
Block a user