-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.py
59 lines (49 loc) · 2.16 KB
/
solution.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
50
51
52
53
54
55
56
57
58
59
class Solution(object):
class MaxHeap(object):
def __init__(self):
self.heap = []
def push(self, value):
self.heap.append(value)
pos = len(self.heap) - 1
p_pos = (pos - 2 if pos % 2 == 0 else pos - 1) / 2
while p_pos >= 0 and value > self.heap[p_pos]:
self.heap[pos], self.heap[p_pos] = self.heap[p_pos], self.heap[pos]
pos = p_pos
p_pos = (pos - 2 if pos % 2 == 0 else pos - 1) / 2
def size(self):
return len(self.heap)
def pop(self):
size = len(self.heap)
if size == 0:
raise IndexError('pop from empty list')
elif size == 1:
return self.heap.pop()
value = self.heap[0]
self.heap[0] = self.heap.pop()
pos = 0
max_child_pos = pos * 2 + 2
if max_child_pos < size - 1:
max_child_pos = max_child_pos if self.heap[max_child_pos] > self.heap[max_child_pos - 1] else max_child_pos - 1
else:
max_child_pos = max_child_pos - 1 if max_child_pos - 1 < size - 1 else pos
while max_child_pos < size - 1 and self.heap[pos] < self.heap[max_child_pos]:
self.heap[pos], self.heap[max_child_pos] = self.heap[max_child_pos], self.heap[pos]
pos = max_child_pos
max_child_pos = pos * 2 + 2
if max_child_pos < size - 1:
max_child_pos = max_child_pos if self.heap[max_child_pos] > self.heap[max_child_pos - 1] else max_child_pos - 1
else:
max_child_pos = max_child_pos - 1 if max_child_pos - 1 < size - 1 else pos
return value
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
max_heap = Solution.MaxHeap()
for num in nums:
max_heap.push(num)
for i in xrange(k - 1):
max_heap.pop()
return max_heap.pop()