我正在尝试查找数组中所有和为k的数对。我目前的解决方案需要 O(n*log(n)) 的时间(以下是代码片段)。有没有人能帮助我找到更好的解决方案,可能是 O(n) 或 O(lgn)(如果存在)
map<int,int> mymap;
map<int,int>::iterator it;
cin>>n>>k;
for( int i = 0 ; i < n ; i++ ){
cin>>a;
if( mymap.find(a) != mymap.end() )
mymap[a]++;
else
mymap[a] = 1;
}
for( it = mymap.begin() ; it != mymap.end() ; it++ ){
int val = it->first;
if( mymap.find(k-val) != mymap.end() ){
cnt += min( it->second, mymap.find(k-val)->second );
it->second = 0;
}
}
cout<<cnt;
first
和last
相加并且结果太大时,应移动哪个迭代器,如果较小应该移动哪一个? - Jarod42