最小的K個數

題目

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

思路

掃描數組,並使用multiset來存儲掃描的元素(從大到小存儲),如果multiset的長度達到k的話,就用新的元素和multiset的第一個元素比較,如果新元素小,則替換進去,否則丟棄。

參考代碼

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