两种方法
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int s = nums.size();
pair<int,int>par[s];
for(int i=0; i<s; ++ i)
{
par[i].first = nums[i];
par[i].second = i;
}
sort(par, par+s);
int b = 0, e = s - 1;
while(b < e)
{
if(par[b].first + par[e].first > target)
e --;
else if(par[b].first + par[e].first < target)
b ++;
else
{
if(par[b].second > par[e].second)
swap(b, e);
return vector<int>{par[b].second, par[e].second};
}
}
}
};
- 存在unordered_map,然后直接find.(复杂度n)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int>mp;
for(int i=0; i<nums.size(); ++i)
mp[nums[i]] = i;
for(int i=0; i<nums.size(); ++ i)
{
int t = target - nums[i];
if(mp.find(t) != mp.end() && mp[t] > i)
{
return vector<int>{i, mp[t]};
}
}
}
};