给定一个整数数组 nums
和一个目标值 target
,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
一、暴力解法:遍历数组,找到与之对应的那个数字
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> twoSum;
for(int i=0;i<nums.size();i++){
for(int j=i+1;j<nums.size();j++){
if((nums[i]+nums[j])==target){
twoSum.push_back(i);
twoSum.push_back(j);
}
}
}
return twoSum;
}
};
二、观察示例可知,当数组是排序好的时候,可以使用一头一尾两个指针进行查找。但是要注意的是最终返回的是数字在没有排序的数组中的位置,而且数组中可能有两个一样的数字。
1.对数组进行排序
2.在排序好的数组,找到那两个数字。如果头尾指针之后大于目标,则尾前移;头尾指针之后小于头后移
3.在没有排序的数组中找这两个数字,注意要考虑这两个数字是否相等,如果不考虑的话,如果两个数字相等,找到的下标是同一个
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> s=nums;
int arr[2];
sort(s.begin(),s.end());//排序,输入不一定都是排序好的
int l=0,r=s.size()-1;
while(l<r){
if(s[l]+s[r]==target){
int ll=find(nums.begin(),nums.end(),s[l])-nums.begin(); //在原来未排序的数组中找数字
if(s[l]==s[r]) nums[ll]--; //可能存在有两个相等的数,不存在三个,因为对应答案只有一个。故如果相等,把一个数减一(消失)
int rr=find(nums.begin(),nums.end(),s[r])-nums.begin();
arr[0]=ll;
arr[1]=rr;
break;
}else if(s[l]+s[r]>target)
r--;
else
l++;
}
return vector<int>(arr,arr+2);
}
};