-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkthElement.py
70 lines (47 loc) · 1.72 KB
/
kthElement.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
60
61
62
63
64
65
66
67
68
69
70
from typing import List
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
self.arrSize = len(nums)
self.heapSort(nums, self.arrSize)
if k == 1:
return nums[-1]
if len(nums) < k:
return nums[-1]
return nums[(-k)]
def parentOfElement(self, i: int) -> int:
return (i/2)
def leftOfElement(self, i: int) -> int:
return (2*i+1)
def rightOfElement(self, i: int) -> int:
return (2*i+2)
def maxHeapify(self, nums: List[int], key: int):
left = self.leftOfElement(key)
right = self.rightOfElement(key)
length = self.arrSize
if left < length and nums[left] > nums[key]:
largest = left
else:
largest = key
if right < length and nums[right] > nums[largest]:
largest = right
if largest != key:
temp = nums[key]
nums[key] = nums[largest]
nums[largest] = temp
self.maxHeapify(nums, largest)
def buildMaxHeap(self, nums: List[int], size: int):
self.arrSize = size
for index in reversed(range(0,(size//2))):
self.maxHeapify(nums, index)
def heapSort(self, nums: List[int], size: int):
self.buildMaxHeap(nums, size)
for i in reversed(range(1, size)):
temp = nums[0]
nums[0] = nums[i]
nums[i] = temp
self.arrSize = self.arrSize - 1
self.maxHeapify(nums, 0)
array = [7,6,5,4,3,2,1]
test = Solution()
result = test.findKthLargest(nums=array, k=2)
print(result)