劍指offer---最小的K個數
阿新 • • 發佈:2018-11-13
題目:最小的K個數
要求:輸入n個整數,找出其中最小的K個數。例如輸入4,5,1,6,2,7,3,8這8個數字,則最小的4個數字是1,2,3,4,。
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
}
};
解題程式碼:
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int > input, int k) {
vector<int> res;
if(k <= 0 || k > input.size()) return res;
int idx =0;
while(idx < k){
res.push_back(input[idx++]);
}
BubbleSort(res);
for(; idx < input.size(); idx++){
if(input[idx] < res[k-1])
res[k-1] = input[idx];
BubbleSort(res);
}
return res;
}
private:
void BubbleSort(vector<int> &array){
bool flag = true;
for(int i = 0; i < array.size() && flag; i++){
flag = false;
for(int j = array.size()-1; j > i; j--){
if(array[j] < array[j-1]){
swap(array[j], array[j-1]);
flag = true;
}
}
}
}
};