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(); for(; iter != data.end(); ++ iter) { if((leastNumbers.size()) < k) leastNumbers.insert(*iter); else { setIterator iterGreatest = leastNumbers.begin(); if(*iter < *(leastNumbers.begin())) { leastNumbers.erase(iterGreatest); leastNumbers.insert(*iter); } } } }
void minKnum2(const vector<int>& data, intSet& leastNumbers, int k) { leastNumbers.clear(); if (k < 1 || data.size() < k) return; vector<int>::const_iterator iter = data.begin(); for (; iter != data.end(); ++iter) { if (leastNumbers.size() < k) leastNumbers.insert(*iter); else { intSetIter iterGreat = leastNumbers.begin(); if (*iter < *(leastNumbers.begin())) { leastNumbers.erase(iterGreat); leastNumbers.insert(*iter); } } } intSetIter iterGreat = leastNumbers.begin(); for (; iterGreat != leastNumbers.end(); ++iterGreat) cout << *iterGreat << " "; }
void GetLeastKNums_2(const vector<int>& data, intSet& leastKNums, int k) { leastKNums.clear(); if(k<1 || data.size() < k) return; vector<int>::const_iterator iter = data.begin(), rear = data.end(); for( ; iter!=rear ; ++iter) { if(leastKNums.size() < k) { leastKNums.insert(*iter); } else { setIterator greatest = leastKNums.begin(); if(*iter < *greatest) { leastKNums.erase(greatest); leasrKNums.insert(*iter); } } } }