劍指offer 面試題40 最小的K個數

題目描述
輸入n個整數,找出其中最小的K個數。例如輸入4,5,1,6,2,7,3,8這8個數字,則最小的4個數字是1,2,3,4,。

tips: 使用C++ STL 中的multiset,維護一個O(k)大小的紅黑樹,時間複雜度O(nlog(n))
學習了set, multiset的基本操作以及內部原理(紅黑樹)

typedef multiset<int,greater<int> > IntSet;
class Solution {
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        vector<int> res;
        if(k<=0||input.size()<k) {
            return res;
        }
        IntSet myset;
        for (int i = 0; i < input.size(); i++)
        {
            if(myset.size()<k) {
                myset.insert(input[i]);
            } else {
                auto iter=myset.begin();
                if(input[i]<(*iter)) {
                    myset.erase((*iter));
                    myset.insert(input[i]);
                }
            }
        }
        
        for (auto iter = myset.end(); iter!= myset.begin(); iter--)
        {
            res.push_back((*iter));
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章