解法一:
若输入数组可以修改,可以基于快速排序的思想找到数组第k个大小的数的位置,返回[0~k-1]位置的数即可。
解法二:
typedef multiset<int, greater<int>> intSet;
typedef multiset<int, greater<int>>::iterator iterSet;
void GetLeastKNumbers(const vector<int>& data, intSet& LeastKNumbers, int k)
{
LeastKNumbers.clear();
if (data.size() < k || k <= 0)
return;
vector<int>::const_iterator iter = data.begin();
for (; iter != data.end(); iter++)
{
if (LeastKNumbers.size() < k)
LeastKNumbers.insert(*iter);
else
{
iterSet iterLargest = LeastKNumbers.begin();
if (*iter < *(LeastKNumbers.begin()))
{
LeastKNumbers.erase(iterLargest);
LeastKNumbers.insert(iter);
}
}
}
}