方法一、用快排的Partitions
时间复杂度 O(n)
vector 参数传递
如果需要在函数中对vector容器中数据调换顺序等操作需要是引用传递
class Solution {
public:
int Partition(vector<int>&a,int low, int high)
{
int x = a[high];
int i =low;
for(int j=low;j<high;j++)
{
if(a[j]<x)swap(a[j],a[i++]);
}
swap(a[i],a[high]);
return i;
}
vector<int> GetLeastNumbers_Solution(vector<int>input, int k)
{
vector<int>V;
if(k>input.size()||k<=0)return V;
int len =input.size();
int low = 0;
int high = len-1;
int index = Partition(input,low,high);
while(index!=k-1)
{
if(index>k-1)
{
high = index-1;
index = Partition(input,low,high);
}
else
{
low = index+1;
index = Partition(input,low,high);
}
}
for(int i=0;i<k;i++)
V.push_back(input[i]);
return V;
}
};
方法二、用最大堆
时间复杂度
O(nlogk)
O
(
n
l
o
g
k
)
(1) 遍历输入数组,将前k个数插入到推中;
(2) 继续从输入数组中读入元素做为待插入整数,并将它与堆中最大值比较:如果待插入的值比当前已有的最大值小,则用这个数替换当前已有的最大值;如果待插入的值比当前已有的最大值还大,则抛弃这个数,继续读下一个数。
这样动态维护堆中这k个数,以保证它只储存输入数组中的前k个最小的数,最后输出堆即可。
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
int len=input.size();
if(len<=0||k>len||k<=0) return vector<int>();
vector<int> res(input.begin(),input.begin()+k);
//建堆
make_heap(res.begin(),res.end());
for(int i=k;i<len;i++)
{
if(input[i]<res[0])
{
//先pop,然后在容器中删除
pop_heap(res.begin(),res.end());
res.pop_back();
//先在容器中加入,再push
res.push_back(input[i]);
push_heap(res.begin(),res.end());
}
}
//使其从小到大输出
sort_heap(res.begin(),res.end());
return res;
}
};