數據是插入到列表中,求中位數,當然是需要排序啊。插入到列表,那插入排序顯然效率最高。
class Solution {
public:
    vector<int> data;
    void Insert(int num) {
        if(data.size() == 0 || data[0] >= num){
            data.insert(data.begin(), num);
            return;
        }
        
        if(data[data.size()-1] <= num){
            data.push_back(num);
            return;
        }
        
        for(int i=1;i<data.size();i++){
            if(data[i] >= num){
                data.insert(data.begin()+i, num);
                break;
            }
        }
    }

    double GetMedian() { 
        int n = data.size();
        if(n == 0){
            return 0;
        }
        
//         printf("-----------------------\n");
//         for(int i=0;i<n;i++){
//             printf("data[%d] = %d,",i,data[i]);
//         }
        if(n % 2 == 0){
            return (data[n/2-1] + data[n/2])/2.0;
        }else{
            return data[n/2];
        }
    }
};

當然還是可以優化的,插入的位置可以二分查找
class Solution {
public:
    vector<int> data;
    void Insert(int num) {
        if(data.size() == 0 || data[0] >= num){
            data.insert(data.begin(), num);
            return;
        }
        
        if(data[data.size()-1] <= num){
            data.push_back(num);
            return;
        }
        
//         for(int i=1;i<data.size();i++){
//             if(data[i] >= num){
//                 data.insert(data.begin()+i, num);
//                 break;
//             }
//         }
        InsertNum(0, data.size()-1, num);
    }

    void InsertNum(int i,int j,int num){
        int m = (i+j)/2;
        if(m == i){
            if(data[i] >= num){
                data.insert(data.begin()+i, num);
            }else{
                if(data[j] >= num){
                    data.insert(data.begin()+j, num);
                }else{
                    data.insert(data.begin()+j+1, num);
                }
            }
        }else{
            if(data[m] < num){
                InsertNum(i,m,num);
            }else{
                InsertNum(m,j,num);
            }
        }
    }
    
    double GetMedian() { 
        int n = data.size();
        if(n == 0){
            return 0;
        }
        
//         printf("-----------------------\n");
//         for(int i=0;i<n;i++){
//             printf("data[%d] = %d,",i,data[i]);
//         }
        if(n % 2 == 0){
            return (data[n/2-1] + data[n/2])/2.0;
        }else{
            return data[n/2];
        }
    }
};