-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmax-heap.py
49 lines (36 loc) · 1002 Bytes
/
max-heap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import doctest
from typing import List
import heapq
# Time Complexity: O(n+klogn)
class Maxheap:
def __init__(self, data=None):
if data is None:
self.data = None
else:
self.data = [-i for i in data]
heapq.heapify(self.data)
def top(self):
return -self.data[0]
def push(self, item):
heapq.heappush(self.data, item)
def pop(self):
return -heapq.heappop(self.data)
def replace(self, item):
return heapq.heapreplace(self.data, -item)
class Solution:
@staticmethod
def findKthLargest(nums: List[int], k: int) -> int:
"""
>>> Solution().findKthLargest([3,2,1,5,6,4],2)
5
>>> Solution().findKthLargest([3,2,3,1,2,4,5,5,6],4)
4
"""
if len(nums) < k:
return -1
maxheap = Maxheap(nums)
while k > 1:
maxheap.pop()
k = k - 1
return maxheap.pop()
doctest.testmod(verbose=2)