mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-06-19 12:24:11 -04:00
Create k_element_stream.py
This commit is contained in:
parent
3eb6a7c828
commit
d6fedcee53
1 changed files with 27 additions and 0 deletions
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…
Add table
Add a link
Reference in a new issue