295. Find Median from Data Stream

JJ·2021년 2월 3일
0

Algorithms

목록 보기
93/114
class MedianFinder {
    public List<Integer> nums;

    /** initialize your data structure here. */
    public MedianFinder() {
        nums = new ArrayList<Integer>();
    }
    
    public void addNum(int num) {
        nums.add(num);
    }
    
    public double findMedian() {
        Collections.sort(nums);
        if (nums.size() % 2 == 1) {
            return (double) nums.get(nums.size() / 2);
        } else {
            double med = nums.get(nums.size() / 2 - 1) + nums.get(nums.size() / 2);
            return med / 2.0;
        }
    }
}

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

Time Limit Exceeded
17 / 18 test cases passed.

흑흑

class MedianFinder {

    private Queue<Long> small = new PriorityQueue(),
                        large = new PriorityQueue();

    public void addNum(int num) {
        large.add((long) num);
        small.add(-large.poll());
        if (large.size() < small.size())
            large.add(-small.poll());
    }

    public double findMedian() {
        return large.size() > small.size()
               ? large.peek()
               : (large.peek() - small.peek()) / 2.0;
    }
}

Runtime: 114 ms, faster than 13.76% of Java online submissions for Find Median from Data Stream.
Memory Usage: 69.7 MB, less than 6.61% of Java online submissions for Find Median from Data Stream.

Heap 사용
기본 queue는 maxHeap!
중간값을 가장 위에다가 두고 갯수가 어긋나면 poll 해서 옮겨주기
마지막에 갯수에 따라서 리턴

0개의 댓글