方法一:Brute Force
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> arr;
if(nums.size() <= 1)
return arr;
for(int i = 0; i<nums.size(); ++i){
for(int j = i+1;j<nums.size();++j){
int rest = target - nums[i];
if(nums[j] == rest){
arr.push_back(i);
arr.push_back(j);
return arr;
}
}
}
}
};
方法二:map( Map是STL的一个关联容器,它提供一对一的数据处理能力)
class Solution{
public:
vector<int> twoSum(vector<int>& nums,int target){
vector<int> ret;
if(nums.size() <= 1)
return ret;
map<int,int> mymap;
for(int i=0;i<nums.size();++i)
mymap[nums[i]]=i;
for(int i=0;i<nums.size();++i){
int rest=target-nums[i];
if(mymap.find(rest)!=mymap.end()){
int index = mymap[rest];
if(index==i)
continue;
if(index<i){
ret.push_back(index);
ret.push_back(i);
return ret;
}else{
ret.push_back(i);
ret.push_back(index);
return ret;
}
}
}
}
};