struct node{
int num,pos;
};
bool cmp(node a,node b){
return a.num<b.num;
}
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<node> copy; //定义node类型的矢量,赋值的时候也是node类型整体赋值,用pushback函数
vector<int> result;
for(int i=0;i<numbers.size();++i){
node t;
t.num=numbers[i];
t.pos=i;
copy.push_back(t);
}
sort(copy.begin(),copy.end(),cmp);//得到排序后保存index的复制数组
//进行查找
int low,high;
low=0;
high=numbers.size()-1;
while(low!=high){
int sum=copy[low].num+copy[high].num;
if(sum>target)
high--;
else if(sum<target)
low++;
else if(sum==target){
if(copy[low].pos<copy[high].pos){
result.push_back(copy[low].pos+1);
result.push_back(copy[high].pos+1);
break;//开始没有加,提示超出内存限制,就是无限循环了
}
else{
result.push_back(copy[high].pos+1);//这个地方犯过错,直接返回high和low了
result.push_back(copy[low].pos+1);
break;
}
}
}
return result;
}
};
需要注意while的结束条件!!
另一种方法
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
map<int,int> copy;
//给map赋值
for(int i=0;i<numbers.size();++i){
copy[numbers[i]]=i;
}
map<int,int>::iterator j=copy.end();//存的是找到的结果,也可以单独设置指针存储?
for(int i=0;i<numbers.size();++i){
j=copy.find(target-numbers[i]);
if(j!=copy.end()&&i<j->second){
result.push_back(i+1);
result.push_back(j->second+1);
break;
}
else if(j!=copy.end()&&i>j->second){
result.push_back(j->second+1);
result.push_back(i+1);
break;
}
}
return result;
}
};
<p style="margin: 10px auto;">很容易忘记的是:map中元素的查找:</p><p style="margin: 10px auto;"> find()函数返回一个迭代器指向键值为key的元素,如果没找到就返回指向map尾部的迭代器。 </p><p style="margin: 10px auto;"> map<int ,string >::iterator l_it;;
l_it=maplive.find(112);
if(l_it==maplive.end())
cout<<"we do not find 112"<<endl;
else cout<<"wo find 112"<<endl;</p>