Skip to content

Latest commit

 

History

History
executable file
·
60 lines (48 loc) · 1.47 KB

295.Find Median from Data Stream.md

File metadata and controls

executable file
·
60 lines (48 loc) · 1.47 KB

295.Find Median from Data Stream

Question

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. For example,

[2,3,4], the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

  • void addNum(int num) - Add a integer number from the data stream to the data structure.
  • double findMedian() - Return the median of all elements so far.
Example:

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2

Thinking:

  • Method 1:
    • 通过堆结构来实现,堆结构是通过优先级队列实现的。
    • 维护一个递增堆和一个递减堆。
    • 通过判断两个堆的size判断总数是奇数还是偶数。
class MedianFinder {
    private List<Integer> list;
    /** initialize your data structure here. */
    public MedianFinder() {
        this.list = new ArrayList<>();
    }

    public void addNum(int num) {
        list.add(num);
    }

    public double findMedian() {
        int size = list.size();
        if(size % 2 != 0)
            return (double)list.get(size / 2);
        else{
            return (double)(list.get(size / 2) + list.get(size / 2 - 1)) / 2;
        }
    }
}

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder obj = new MedianFinder();
 * obj.addNum(num);
 * double param_2 = obj.findMedian();
 */