【Java】劍指Offer_編程題_數據流中的中位數

題目鏈接:https://www.nowcoder.com/questionTerminal/9be0172896bd43948f8a32fb954e1be1

題目描述
如何得到一個數據流中的中位數?如果從數據流中讀出奇數個數值,那麼中位數就是所有數值排序之後位於中間的數值。如果從數據流中讀出偶數個數值,那麼中位數就是所有數值排序之後中間兩個數的平均值。我們使用Insert()方法讀取數據流,使用GetMedian()方法獲取當前讀取數據的中位數。

第一次編輯代碼:

import java.util.*;
public class Solution {
    int index = 0;
    int cap = 0;
    int [] ans = new int [100];
    public void Insert(Integer num) {
        ans[index++] = num;
        cap++;
    }

    public Double GetMedian() {
        Arrays.sort(ans);
        if(cap%2 == 0){
            return (double)(ans[cap/2] + ans[cap/2+1])/2;
        }else{
            return (double)ans[cap/2];
        }
    }
}

提交結果
答案錯誤:您提交的程序沒有通過所有的測試用例

反思
這我是沒想到的。

第二次編輯代碼:

import java.util.*;
public class Solution {
    int cap = 0;
    PriorityQueue<Integer> low = new PriorityQueue<Integer>();
    PriorityQueue<Integer> high = new PriorityQueue<Integer>(new Comparator<Integer>(){
        public int compare(Integer o1,Integer o2){
            return o2.compareTo(o1);
        }
    });
    public void Insert(Integer num) {
        cap++;
        if(cap%2 != 0){
            if(!low.isEmpty() && num>low.peek()){
                low.offer(num);
                num = low.poll();
            }
            high.offer(num);
        }else{
            if(!high.isEmpty() && num<high.peek()){
                high.offer(num);
                num = high.poll();
            }
            low.offer(num);
        }
    }

    public Double GetMedian() {
        double ans;
        if(cap%2 != 0){
            ans = high.peek();
        }else{
            ans = (low.peek()+high.peek())/2.0;
        }
        return ans;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章