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
Output: index1=1, index2=2
Key:
1.MAP
<K, V>为<值,下标>,map中保存的是已经扫描过的number。 这是一种很直观很自然的做法: 对于numbers[i],如果map中存在K=target-numbers[i],则要求的解为V(K=target-numbers对应的)和i;如果不存在,则向map中添加<numbers[i], i>。
查找最快的方法是利用一个 map容器存储每个元素的索引,这样取得某个特定元素的索引只需要常数时间即可完成,这样就更快了,最多只需遍历一次序列,将元素及其索引加入map中,在遍历的过程中进行对应差值的查找,如果找到了就结束遍历,这样时间复杂度最多为 O(N),It's amazing!
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> a;
map<int,int>numbersMap;
for(int i=0;i!=numbers.size();++i)
{
auto iter=numbersMap.find(target-numbers[i]);
if(iter !=numbersMap.end())
{
a.push_back(iter->second);
a.push_back(i+1);
}
else
{
numbersMap[numbers[i]]=i+1;
}
}
return a;
}
};
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> a;
map<int,int>numbersMap;
for(int i=0;i!=numbers.size();++i)
{
auto iter=numbersMap.find(target-numbers[i]);
if(iter !=numbersMap.end())
{
a.push_back(iter->second);
a.push_back(i+1);
}
else
{
numbersMap[numbers[i]]=i+1;
}
}
return a;
}
};
2.数组
我们可以先将vector复制一份,对新复制的vector排序,然后直接找到这样的两个数之和等于目标数值,然后再去数组中找寻两个加数的下标。
int i,j;
vector<int>nums(numbers);
vector<int>index(2,0);
sort(nums.begin(),nums.end());//默认采用升序排序
i = 0;
j = nums.size()-1;
while(i<j)
{
if (nums[i]+nums[j]<target)
i++;
else if(nums[i]+nums[j]>target)
j--;
else if(nums[i]+nums[j]==target)
break;
}
//一个从前往后找,一个从后往前找,避免两个数是同一个值,测试用例{0,4,5,0} target = 0
int temp = 0;
while(temp < nums.size())
{
if (numbers[temp]== nums[i])
{
index[0]=temp+1;
break;
}
temp ++;
}
temp = nums.size()-1;
while(temp >=0)
{
if (numbers[temp]== nums[j])
{
index[1]=temp+1;
break;
}
temp --;
}
//这一步检查是为了防止小的数在大的数后面,测试用例,16,2,3,4,5,7,8} target=20
if(index[0]>index[1])
{
temp = index[0];
index[0]=index[1];
index[1]=temp;
}
return i;
vector<int>nums(numbers);
vector<int>index(2,0);
sort(nums.begin(),nums.end());//默认采用升序排序
i = 0;
j = nums.size()-1;
while(i<j)
{
if (nums[i]+nums[j]<target)
i++;
else if(nums[i]+nums[j]>target)
j--;
else if(nums[i]+nums[j]==target)
break;
}
//一个从前往后找,一个从后往前找,避免两个数是同一个值,测试用例{0,4,5,0} target = 0
int temp = 0;
while(temp < nums.size())
{
if (numbers[temp]== nums[i])
{
index[0]=temp+1;
break;
}
temp ++;
}
temp = nums.size()-1;
while(temp >=0)
{
if (numbers[temp]== nums[j])
{
index[1]=temp+1;
break;
}
temp --;
}
//这一步检查是为了防止小的数在大的数后面,测试用例,16,2,3,4,5,7,8} target=20
if(index[0]>index[1])
{
temp = index[0];
index[0]=index[1];
index[1]=temp;
}
return i;