其他分享
首页 > 其他分享> > Heap 相关

Heap 相关

作者:互联网

295. Find Median from Data Stream Hard

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.

Implement the MedianFinder class:

 

Example 1:

Input
["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [1], [2], [], [3], []]
Output
[null, null, null, 1.5, null, 2.0]

Explanation
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1);    // arr = [1]
medianFinder.addNum(2);    // arr = [1, 2]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3);    // arr[1, 2, 3]
medianFinder.findMedian(); // return 2.0

Constraints:

解法: 一个大顶堆(存前半段元素),一个小顶堆(存后半段元素),那么取中位数只需要从堆顶取即可

时间复杂度:

Follow up:

解法:可以直接开个int[100]数组,插入元素进行count[i]++, 查找的时候根据count找到最终的中位数 ,插入和查找 都为O(1) 

解法:可以把数据分3段:  x < 0 (使用maxheap), x in 0 ~ 100 (使用数组count), x > 100  (使用minheap)

class MedianFinder {
    private PriorityQueue<Integer> minHeap;
    private PriorityQueue<Integer> maxHeap;
    
    public MedianFinder() {
        minHeap = new PriorityQueue<Integer>((x,y)->x-y);//小顶堆,存后半段
        maxHeap = new PriorityQueue<Integer>((x,y)->y-x);//大顶堆,存前半段
    }
    
    public void addNum(int num) {//O(logN)
        if(maxHeap.isEmpty() || maxHeap.peek()>num) maxHeap.offer(num);//如果小于大顶堆top,放前半段
        else minHeap.offer(num);//否则放后半段
        //保持两堆数量平衡,或者大顶堆多一个
        while(minHeap.size()>maxHeap.size()) maxHeap.offer(minHeap.poll());
        while(minHeap.size()<maxHeap.size()-1) minHeap.offer(maxHeap.poll());
    }
    
    public double findMedian() {//O(1)
        //如果数量一样,去各自头取平均
        if(minHeap.size()==maxHeap.size()) return ((double)minHeap.peek()+(double)maxHeap.peek())/2;
        //奇数个直接去大顶堆top,因为奇数时肯定大顶堆元素多一个
        return maxHeap.peek();
    }
}

 

标签:maxHeap,addNum,findMedian,num,Heap,minHeap,相关,MedianFinder
来源: https://www.cnblogs.com/cynrjy/p/15862428.html