Heap is a tree-like data structure. Every node must satisfy the heap property (max/min/etc). In java, heap is implemented as PriorityQueue<>(size, Comparator
Article Language: English
Example Language: Java
Reading Time: 11min
Implement a Heap Using Array
Constructor takes different parameters, with default capacity and heapify input array. Implements basic operations, offer, poll, peek, size, and isEmpty. With resize function, the priority queue can expand its capacity when it’s half full. The amortized time complexity for offer and poll remain constant.
1 | public class MyPQ { |
Heapify
input:
an int array.output:
none.
A min heap must satisfy following property, for a list of n elements {k1, k2… ki…kn}, (ki <= k2i, ki <= k2i+1)或者(ki >= k2i, ki >= k2i+1), (i = 1, 2, 3, 4… n/2).
In other words,
- left child (node * 2 + 1)
- right child (node * 2 + 2)
must not greater than node.
1 | public class Heapify { |
Merge K Sorted Lists
input:
lists of sorted linked list.output:
one sorted linked list.
The most intuitive way of solving this problems is that merge lists two by two. Since there are soreted linked list, recursively call a helper function and merge. Problem is that every node is visited more than one time.
Another approach is using heap. Only keep the reference of head of the linked list. It taks O(k) to build min heap. Offer and poll operation take O(lok). There a k lists and every list has n nodes. The time complexity is O(knlogk). Space complexity is O(k) for list nodes in the priority queue.
1 | public class MergeKLists { |
Merge K sorted arrays
input:
list of sorted arrays.output:
one sorted array.
Similar to merge linked list. Only difference is that element in the array doesn’t have reference to its neightbor. Creating a cell class with all information about an element’s neighbor. Using priority queue to store first element of each row because the rows in the 2D array may not have the same number of column.
The time complexity is O(Nlogk) where N is the totol number of input and k is the number of arrays.
1 | ublic class MergeKArrays { |
High Five
input:
list of Records with id and score.output:
return the average of top 5 score for each id.
Extra data structure needs to be used here to record scores for each id, and the average of score for the id. Using two maps, for list of scores, and another one for final result.
It asks top 5 score. Intuitively, top number of something fits the property of max heap. Using priority queue to record scores, calculate averate of top 5 numbers. Time compexity is O(n) for store all data from the input. O(knlogn) for poping k times (5) for each id, and calculate the average. Therefore, the total time complexity is O(knlogn). Space used here besides the ouput is the map that used to store data, which is O(n).
1 | /** |