数组中 最小K个数
1 基于快排中 partition函数的思想
一定要注意那里是对容器的地址 或者引用操作 否则传不出来!!!
public: vector<int> GetLeastNumbers_Solution(vector<int> input, int k) { vector<int> result; if(input.empty() || k>input.size() || k<=0) return result; int start = 0; int end = input.size()-1; int index = partition(input,start,end); while(index != (k-1)) { if(index > (k-1)) { end = index - 1; index = partition(input,start,end); } else { start = index + 1; index = partition(input,start,end); } } for(int i=0;i<k;++i) { result.push_back(input[i]); } return result; } int partition(vector<int> &numbers,int low,int high) { int pivotkey=numbers[low];//当参考值 while(low<high) { while(low<high&&numbers[high]>pivotkey) {high--;} swap(numbers[low],numbers[high]); while(low<high&&numbers[low]<=pivotkey) { low++;} swap(numbers[low],numbers[high]); } return low; } void swap(int &A,int &B) { int temp; temp=A; A=B; B=temp; }
方法2 基于muiltiset 红黑树 最大堆排序
// ====================方法2==================== typedef multiset<int, greater<int> > intSet;//greater函数和less相反,这个谓词 typedef multiset<int, greater<int> >::iterator setIterator;//设置迭代器 void GetLeastNumbers_Solution2(const vector<int>& data, intSet& leastNumbers, int k) { leastNumbers.clear();//清空 if (k < 1 || data.size() < k) return; vector<int>::const_iterator iter = data.begin();//vector迭代器 for (; iter != data.end(); ++iter) { if ((leastNumbers.size()) < k) leastNumbers.insert(*iter); else { setIterator iterGreatest = leastNumbers.begin();//multiset迭代器 if (*iter < *(leastNumbers.begin())) { leastNumbers.erase(iterGreatest);//删除该条目 leastNumbers.insert(*iter);//插入新的,自动排序 } } } }