Heap intro
Question
Q1 Find smallest kth elements form an unsorted array(size n)
Representation of graph
图里常见的search
经典例题BFS-1:Level order
get Keys in binary tree layer by layer
Solution 1: MinHeap
Solution 2: MaxHeap
Step 1: Heapify the first k elements to form a MaxHeap of size = k. O(k)
Step 2: Iterate over the remain elements one by one. O((n-k) * logk)
TC: O(k + (n - k) * logk)
Adjacency matrix
Adjacency list O(V)
HashMap<Node, Set<Node>>
List<GraphNode>: O(v)
public class solution {
public List<List<Integer>> LayerByLayer(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
if (root == null) {
return list;
}
//用一个queue来装整棵树
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
List<Integer> curLayer = new ArrayList<>();
int size = queue.size;
for (int i = 0; i < size; i++) {
TreeNode cur = queue.poll();
curLayer.add(cur.key);
if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
}
list.add(curLayer);
}
return list;
}
TC: O(n)
SC: O(n)
<aside> 💡 dijkstra’s algorithm 的重要性质
<aside> 📌 SUMMARY:
</aside>
K Smallest in unsorted Array
definition
It's a heap with the same Queue interface with offer(), peek(), and poll()
But it’s not FIFO, when poll() or Peek() we always look at the smallest or largest element
内存里存放方法:array
对应Java class:Priority Queue
对应Interface: Queue
Method 1: MaxHeap
Method 2: MinHeap
两种方式provide a comparator class or set class with natural ordering
public int compareTo(Integer anotherInt)
return:
- 0,两者相等
- -1, this.Integer < anotherInt
- 1, this.Integer > anotherInt
eg. Integer a = new Integer(10);
Integer b = new Integer(20);
Ststem.out.println(a.compareTo(b)); -1;
Declaration: PriorityQueue<MyInteger> pq = new PriortyQueue<>( );
<aside> 📌 SUMMARY:
</aside>
<aside> 📌 SUMMARY:
</aside>