1. 程式人生 > 其它 >Windows配置定時休眠和喚醒

Windows配置定時休眠和喚醒

中位數是有序列表中間的數。如果列表長度是偶數,中位數則是中間兩個數的平均值。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/find-median-from-data-stream
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

import java.util.Comparator;
import java.util.PriorityQueue;

class MedianFinder {

    private PriorityQueue<Integer> leftQueue = new PriorityQueue<>(new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return Integer.compare(o2, o1);
        }
    });

    private PriorityQueue<Integer> rightQueue = new PriorityQueue<>();

    public MedianFinder() {

    }

    public void addNum(int num) {
        if (leftQueue.isEmpty() || num <= leftQueue.peek()) {
            leftQueue.offer(num);
            while (leftQueue.size() > rightQueue.size() + 1) {
                rightQueue.offer(leftQueue.poll());
            }
        } else {
            rightQueue.offer(num);
            while (rightQueue.size() > leftQueue.size()) {
                leftQueue.offer(rightQueue.poll());
            }
        }
    }

    public double findMedian() {
        int length = leftQueue.size() + rightQueue.size();
        if (length % 2 == 0) {
            return (leftQueue.peek() + rightQueue.peek()) / 2.0;
        } else {
            return leftQueue.peek();
        }
    }
}

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder obj = new MedianFinder();
 * obj.addNum(num);
 * double param_2 = obj.findMedian();
 */
心之所向,素履以往 生如逆旅,一葦以航