defmergeKLists(self,lists: List[ListNode]) -> ListNode:ifnot lists:returnNone inter =1 total =len(lists)while inter < total:for i inrange(0, total - inter, inter*2): lists[i]= self.merge2List(lists[i], lists[i+inter]) inter *=2return lists[0]defmerge2List(self,l1,l2): dummy = cur =ListNode(0)while l1 and l2:if l1.val < l2.val: cur.next = l1 l1 = l1.nextelse: cur.next = l2 l2 = l2.next cur = cur.nextif l1: cur.next = l1if l2: cur.next = l2return dummy.next
295 Find median from Data Stream
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
Use 2 heaps, a maxHeap to store left half data, a minHeap to store right half data
A boolean flag to record odd or even
Time: O(logn)
classMedianFinder {Queue<Integer> lo;Queue<Integer> hi;boolean isOdd; /** initialize your data structure here. */publicMedianFinder() { lo =newPriorityQueue<>(1, (a,b) -> b-a); hi =newPriorityQueue<>(); }publicvoidaddNum(int num) {lo.add(num);int max =lo.poll();hi.add(max); isOdd =false;if (hi.size() >lo.size()){lo.add(hi.poll()); isOdd =true; } }publicdoublefindMedian() {if (isOdd){returnlo.peek(); }else{return ((double)lo.peek() + (double)hi.peek()) /2; } }}
253. Meeting Rooms II
find the minimum number of conference rooms required.
Sort the intervals by inter.start time
Put 1st inter.end in the heap
Peak pre ending time and current start time to determine to pop a room