输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
思路1:先对数组从小达到进行排序,输出前k个数。快速排序,时间复杂度:O(nlogn)。
代码提交页
代码:
class Solution {
public:
vector GetLeastNumbers_Solution(vector input, int k) {
int len = input.size();
int low=0;
int high=len-1;
vector res;
if(len<=0 || k>len) return res;
quick_sort(input, low, high);
for(int i=0; i& output, int start, int end)
{
int index=start;
int i=start;
int j=end;
int base=output[index];
while(i=base) j--;
output[i]=output[j];
while(i1) quick_sort(output, start, i-1);
if(end-j>1) quick_sort(output, j+1, end);
}
};
思路2:使用partition函数(进行一次快速排序,用哨兵数分割数组中的数据),时间复杂度:O(n)
代码:
class Solution {
public:
vector GetLeastNumbers_Solution(vector input, int k) {
vector res;
int high = input.size()-1;
int low = 0;
if((high+1)& nums, int low, int high)
{
if(low<0 || high>nums.size() || low>high) return -1;
if(low==high) return low;
int base=nums[low];
while(low=base) high--;
nums[low]=nums[high];
while(low
思路3:小顶堆(优先队列),时间复杂度:O(nlog(k)).
STL中的优先队列默认是大顶堆,这里生成小顶堆即可。
模板申明带3个参数:priority_queue
c.top() |
返回队列头部数据 |
c.push(elem) |
在队列尾部增加elem数据 |
c.pop() |
队列头部数据出队 |
代码:
class Solution {
public:
vector GetLeastNumbers_Solution(vector input, int k) {
vector res;
if(k<=0 || k>input.size()) return res;
priority_queue q; // STL中的优先队列默认是大顶堆
unsigned int i=0;
while(ik) q.pop();
i++;
}
while(!q.empty())
{
res.push_back(q.top()); // C语言中的top()可返回顶部元素的值,也可返回顶部元素的指针,程序员自行设计; C++的STL中top()返回的是顶部的值
q.pop();
}
return res;
}
};