标签:color list 数据流 java vat HERE tco EAP collect
一:解题思路
方法一:每次添加一个数字,都使它成为一个递增有序的序列。时间复杂度分别为:addNum:O(n),findMedian:O(1)
方法二:采用一个最小堆和一个最大堆。时间复杂度分别为:addNum:O(log(n)),findMedian:O(1)
二:完整代码示例 (C++版和Java版)
方法一C++:
方法一Java:
class MedianFinder { private List<Integer> m_data=new ArrayList<>(); /** initialize your data structure here. */ public MedianFinder() { } public void addNum(int num) { int idx=m_data.size()-1; while (idx>=0 && m_data.get(idx)<num) idx--; m_data.add(idx+1,num); } public double findMedian() { int n=m_data.size(); if((n&1)==1) return m_data.get(n/2); else return (m_data.get(n/2-1)+m_data.get(n/2))/2.0; } }
方法二C++:
class MedianFinder { private: priority_queue<int, vector<int>, greater<int>> minHeap; priority_queue<int, vector<int>, less<int>> maxHeap; public: /** initialize your data structure here. */ MedianFinder() { } void addNum(int num) { minHeap.push(num); maxHeap.push(minHeap.top()); minHeap.pop(); if (maxHeap.size() - minHeap.size() > 1) { minHeap.push(maxHeap.top()); maxHeap.pop(); } } double findMedian() { if (maxHeap.size() > minHeap.size()) { return maxHeap.top(); } else { return (maxHeap.top()+minHeap.top()) / 2.0; } } };
方法二Java:
class MedianFinder { private Queue<Integer> minHeap=new PriorityQueue<>(); private Queue<Integer> maxHeap=new PriorityQueue<>(Collections.reverseOrder()); /** initialize your data structure here. */ public MedianFinder() { } public void addNum(int num) { minHeap.add(num); maxHeap.add(minHeap.poll()); if(maxHeap.size()-minHeap.size()>1) { minHeap.add(maxHeap.poll()); } } public double findMedian() { if(maxHeap.size()>minHeap.size()) { return maxHeap.peek(); } else { return (maxHeap.peek()+minHeap.peek())/2.0; } } }
标签:color list 数据流 java vat HERE tco EAP collect
原文地址:https://www.cnblogs.com/repinkply/p/12732999.html