value in any node is less than its decendent and root is the least element
complete binary tree
Max Heap means root is maximum element, Min Heap means root is minimum element
unsorted bu follow rules above
Operation
insert, put the element in the last and swap up, O(logn)
update, O(logn)
get/top, get the root element, O(1)
pop, delete the root element, O(logn) put the last element to the root
heapify: transform unsorted array to a heap, O(n)
Python Lib
min heap
heapq.heapify(iterable), O(c * n) This function is used to convert the iterable into a heap data structure. i.e. in heap order.
heapq.heappush(heap, ele), O(logn) This function is used to insert the element mentioned in its arguments into heap. The order is adjusted, so as heap structure is maintained.
heapq.heappop(heap), O(logn) This function is used to remove and return the smallest element from heap. The order is adjusted, so as heap structure is maintained.
heapq.heappushpop(heap, ele) This function combines the functioning of both push and pop operations in one statement, increasing efficiency. Heap order is maintained after this operation.
heapq.heapreplace(heap, ele) This function also inserts and pops element in one statement, but it is different from above function. In this, element is first popped, then element is pushed.i.e, the value larger than the pushed value can be returned.
heapq.nlargest(k, iterable, key = fun) This function is used to return the k largest elements from the iterable specified and satisfying the key if mentioned.
heapq.nsmallest(k, iterable, key = fun) This function is used to return the k smallest elements from the iterable specified and satisfying the key if mentioned.
classSolution: defgetSkyline(self, buildings): positions = set([b[0] for b in buildings] + [b[1] for b in buildings]) res = [[0, 0]] live = [] i = 0 for p in sorted(positions): # Keep all the position before p to the heap "live" while i < len(buildings) and buildings[i][0] <= p: heapq.heappush(live, (-buildings[i][2], buildings[i][1])) i += 1
# Keep the maximum height's position > p while live and live[0][1] <= p: heapq.heappop(live)
h = -live[0][0] if live else0 if h != res[-1][1]: res.append([p, h]) return res[1:]