题解 | #最小的K个数#
最小的K个数
https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param input int整型vector
* @param k int整型
* @return int整型vector
*/
vector<int> GetLeastNumbers_Solution(vector<int>& input, int k) {
// write code here
int index;
vector<int> temp = input;
vector<int> res;
// 排除特殊情况
if (k == 0) {
return res;
}
// 输出数组中有k个元素,时间复杂度o(k)
for (int i = 0; i < k; i++) {
// 寻找数组中的最小值,时间复杂度o(n)
int minc = 1e9;
for (int j = 0; j < temp.size(); j++) {
if (temp[j] < minc) {
minc = temp[j];
index = j;
}
}
// 加入输出结果中
res.push_back(minc);
// 将最小值从temp数组中去掉,在新数组中继续找最小值
for (int k = index + 1; k < temp.size(); k++) {
temp[k - 1] = temp[k];
}
temp.reserve(temp.size() - 1);
}
return res;
}
};
查看14道真题和解析