Introduction
Priority Queue
https://www.youtube.com/watch?v=t0Cq6tVNRBA&list=PLUL4IRMCZfeXjd5AzDyry39Mf_pn1YLjQ
Time Complexity
- Find min/max: O(1)
- Delete min/max: O(log(n))
- Insert: O(log(n))
Implementation
Python Queue
: https://docs.python.org/3/library/queue.html#queue.PriorityQueue
1 | from Queue import PriorityQueue |
Python heapq
: https://docs.python.org/2/library/heapq.html (use a priority queue to implemented a min heap)
1 | from heapq import * |
347. Top K Frequent Elements
Leetcode: https://leetcode.com/problems/top-k-frequent-elements/description/
[Solution] Build a hashmap to record the frequency of numbers, and use MaxHeap to sort the elements in the HashMap
1 | class Solution { |
692. Top K Frequent Words
[Solution] Same as above
1 | class Solution { |
295. Find Median from Data Stream
[Solution]:
- Use two heaps one min one max to store elements to the left of median and to the right of the median.
1 | from heapq import * |
Use heap
to optimize sorting
23. Merge k Sorted Lists
Leetcode: https://leetcode.com/problems/merge-k-sorted-lists/
Time Complexity: O(nlogk), where k is the number of linked list.
1 | from heapq import * |
253. Meeting Rooms II
Leetcode: https://leetcode.com/problems/meeting-rooms-ii/
Solution: Use heap to optimize min
function
1 | from heapq import * |