题目描述:
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
首先要考虑特殊情况 数组为空 或K为0 或K大于数组长度。
接下来考虑用什么方法进行排序。
1、使用C++标准库sort
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> tmp;
if(input.empty() || k == 0 || k > input.size()) return tmp;
sort(input.begin(), input.end());
tmp.assign(input.begin(), input.begin() + k);
return tmp;
}
};
标准库中的sort函数默认是从小到大排序。若要实现从大到小排序,需要加入第三个参数greater<int>()。
分析一下时间复杂度吧。std::sort
必须具有平均情况线性O(n log n)时间复杂度。
2、快排
class Solution {
public:
int Partition(vector<int>& v, int low, int high){
int pivot = v[low];
while(low < high){
while(low < high && v[high] >= pivot) high--;
v[low] = v[high];
while(low < high && v[low] <= pivot) low++;
v[high] = v[low];
}
v[low] = pivot;
return low;
}
void QuickSort(vector<int>& v, int low, int high){
if(low < high){
int pivotpos = Partition(v, low, high);
QuickSort(v, low, pivotpos - 1);
QuickSort(v, pivotpos + 1, high);
}
}
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> tmp;
if(input.empty() || k == 0 || k > input.size()) return tmp;
QuickSort(input, 0, input.size() - 1);
tmp.assign(input.begin(), input.begin()+k);
return tmp;
}
};
时间复杂度:O(nlog2n)。