Skip to content

Instantly share code, notes, and snippets.

@adamgarcia4
Created August 16, 2020 20:02
Show Gist options
  • Select an option

  • Save adamgarcia4/b2a529793e3a90616db9583433105f22 to your computer and use it in GitHub Desktop.

Select an option

Save adamgarcia4/b2a529793e3a90616db9583433105f22 to your computer and use it in GitHub Desktop.
class Heap:
def __init__(self, arr = None):
self.arr = arr or []
def __bool__(self):
return bool(self.arr)
def __getitem__(self, key):
return self.arr[key]
def bubbleup(self, idx):
# index at root node. Cannot bubble up any further
if idx == 0:
return
parentIndex = (idx - 1) // 2
if self.arr[idx] > self.arr[parentIndex]:
self.arr[idx], self.arr[parentIndex] = self.arr[parentIndex], self.arr[idx]
self.bubbleup(parentIndex)
def bubbledown(self, idx):
# bubble down with the largest of the children
left = 2 * idx + 1
right = 2 * idx + 2
# Reached a leaf, so stop
if left > len(self.arr) - 1 and right > len(self.arr) - 1:
return
# pick the larger of the two children to perform the swap.
maxChildIdx = left
# node guranteed to have at least a left b/c completely filled in order.
if right < len(self.arr) and self.arr[right] > self.arr[left]:
maxChildIdx = right
if self.arr[idx] < self.arr[maxChildIdx]:
self.arr[idx], self.arr[maxChildIdx] = self.arr[maxChildIdx], self.arr[idx]
self.bubbledown(maxChildIdx)
def heappush(self, val):
self.arr.append(val)
self.bubbleup(len(self.arr) - 1)
def heappop(self):
temp = self.arr[0]
self.arr[0], self.arr[-1] = self.arr[-1], self.arr[0]
del self.arr[-1]
self.bubbledown(0)
return temp
class Solution:
def testHeap(self):
heap = Heap()
heap.heappush(4)
heap.heappush(3)
heap.heappush(6)
heap.heappush(10)
heap.heappush(1)
heap.heappush(11)
heap.heappush(12)
heap.heappush(-4)
while heap:
print(heap.heappop())
def findKthLargest(self, nums: List[int], k: int) -> int:
'''
3,2,1,5,6,4
(v )
x,x,x,x,|x,x|
1,2,3,4,(5),6
{6,5}
'''
# maintain min heap of size 'k'
heap = Heap()
for i in range(k):
heap.heappush(-1 * nums[i])
# Now my heap is of size 'k'
# only replace an element if it is > than the head
for i in range(k, len(nums)):
if nums[i] > -1 * heap[0]:
heap.heappop()
heap.heappush(-1 * nums[i])
return -1 * heap[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment