劍指Offer學習-面試題41:數據流中的中位數

	public static void main(String[] args) {
        while (true) {
            Scanner input = new Scanner(System.in);
            System.out.println("請輸入一個正整數:");
            int cur = input.nextInt();
            System.out.println("此時的中位數是:" + getMid(cur));
        }
    }


    static PriorityQueue<Integer> max = new PriorityQueue<>((a, b) -> b - a);
    static PriorityQueue<Integer> min = new PriorityQueue<>();

    /**
     * 數據流中的中位數
     *
     * @return
     */
    public static int getMid(int cur) {
        int maxSize = max.size();
        int minSize = min.size();
        if (minSize == 0) {
            min.add(cur);
            return cur;
        }
        if (maxSize == 0) {
            if (min.peek() < cur) {
                max.add(min.poll());
                min.add(cur);
            } else {
                max.add(cur);
            }
            return (min.peek() + max.peek()) / 2;
        }
        if (cur > min.peek()) {
            min.add(cur);
            minSize += 1;
        } else {
            max.add(cur);
            maxSize += 1;
        }
        if (Math.abs(maxSize - minSize) >= 2) {
            if (maxSize > minSize) {
                min.add(max.poll());
            } else {
                max.add(min.poll());
            }

        }
        if ((maxSize + minSize) % 2 == 0) {
            return (min.peek() + max.peek()) / 2;
        }
        return maxSize > minSize ? max.peek() : min.peek();

    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章