剑指offer给出两类方法:
1,借助快排的思想,需要修改输入数组的元素,时间复杂度O(n)
2,借助STL中set或者multiset,因为它们的底层数据结构是红黑树实现的,插入数据时间复杂度为O(logk),所以总的时间复杂度为O(nlogn);
==========
方法2的代码如下:
typedef std::multiset<int,greater<int> > intset; typedef std::multiset<int,greater<int> >::iterator iteratorset; void getLeastNumber(vector<int> nums,intset& leastNumber,int k){ int length = nums.size(); leastNumber.clear(); if(length <k) return; for(auto i:nums){ if(leastNumber.size()<(unsigned int)k){ leastNumber.insert(i); }else{ iteratorset itset = leastNumber.begin(); if(i<*itset){ leastNumber.insert(i); leastNumber.erase(leastNumber.begin()); } }///if-else }///for }///end-function