给定一个长度为 n 的可能有重复值的数组,找出其中不去重的最小的 k 个数。例如数组元素是4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4(任意顺序皆可)。
#include <iostream>using namespace std; #include <stack>
#include <string>
#include <queue>
#include <vector>vector<int> GetLastKNumbers(vector<int>& input, int k)
{if (input.empty() || k <= 0)return std::vector<int>{};std::priority_queue<int> queue;for (int i = 0; i < k; i++){queue.push(input[i]);}for (int i = k; i < input.size(); i++){if (queue.top() > input[i]){queue.pop();queue.push(input[i]);}}std::vector<int> res{};for (int i = 0; i < k; i++){res.push_back(queue.top());queue.pop();}return res;
}int main()
{std::vector<int> input = { 4,5,1,6,2,7,3,8 };std::vector<int> output = GetLastKNumbers(input, 4);for (auto o : output)std::cout << o << " "; std::cout<< std::endl;return 0;
}