问题描述:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
即给一个数组、一个结果,求数组中的哪两个加起来等于那个结果,返回这两个的下标。假设只有一个答案,并且返回的下标不能相同
问题样例:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].问题解决:
用两层循环遍历数组,让每一个数字都和它后面的数字相加,若判断到加起来和结果相同,则返回下标
代码如下
class Solution {public:
vector<int> twoSum(vector<int>& nums, int target) {
//由于用的是vector所以用迭代器遍历
vector<int>::iterator iter1;
//记录第一个数的下标
int indices1 = 0;
for (iter1=nums.begin();iter1!=nums.end();iter1++,indices1++)
{
vector<int>::iterator iter2 = iter1+1;
//记录第二个数的下标
int indices2 = indices1+1;
for(;iter2!=nums.end();iter2++,indices2++) {
//若加起来等于结果,返回下标
if(*iter1 + *iter2 == target) {
int a[2]={indices1,indices2};
vector<int> result(a,a+2);
return result;
}
}
}
}
};