双指针
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n=nums.size();
int pre=0,back=n-1;
vector<int> out;
while(pre<back){
if(nums[pre]+nums[back]>target){
back--;
}else if(nums[pre]+nums[back]<target){
pre++;
}else{
out.push_back(nums[pre]);
out.push_back(nums[back]);
break;
}
}
return out;
}
};
哈希表
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_set<int>hashset;
vector<int> out;
for(int n:nums){
auto it=hashset.find(target-n);
if(it!=hashset.end()){
out.push_back(target-n);
out.push_back(n);
break;
}else{
hashset.insert(n);
}
}
return out;
}
};