1.题目描述
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
在数组中找到两个数,使这两个数的和等于目标值。
2.分析
思路一:
首先想到用map映射来做。map<int,int>中,key记录数组的值,value记录下标。遍历nums数组,在map中找到target-nums[i],如果找到,则返回下标。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> mp;
vector<int> ans;
for (int i = 0; i < nums.size(); i++)
mp[nums[i]] = i;
for(int i=0;i<nums.size();i++)
{
if(mp.find(target-nums[i])!=mp.end() && i!=mp.find(target-nums[i])->second)
{
ans.push_back(i+1);
ans.push_back((mp.find(target-nums[i])->second)+1);
break;
}
}
return ans;
}
};
思路二:
用“逼近”的算法。首先新建一个数组存储原数组的值,再将新建的数组排序。用temp表示。然后left从左至右扫描,right从右至左扫描。
我们可以知道,如果temp[left]+temp[right]>target,那么肯定有一个数大了,那么就使right--;
同样,如果temp[left]+temp[right]<target,那么肯定有一个数小了,使left++;
如果相等,则找到了要找的数,但是这里的left和right并不是原数组的下标,所以还得在原数组中再找一遍。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> temp = nums;
sort(temp.begin(),temp.end());
int left = 0;
int right = temp.size()-1;
while(temp[left]+temp[right] != target)
{
if(temp[left]+temp[right] > target)
right--;
else
left++;
}
vector<int> array(2,0);
for(int i=0;i<temp.size();i++)
{
if(nums[i] == temp[left] || nums[i] == temp[right])
if(array[0] == 0)
array[0] = i+1;
else
array[1] = i+1;
}
return array;
}
};