题目要求:
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Subscribe to see which companies asked this question.
思路:
将target-nums的差保存,并在nums中查找该差值,找到时输出nums所在下标和差所在下标即可,如代码1所示。
查找差值时,可使用二分查找算法,如代码2所示。
代码1如下:
#include<iostream>
#include<vector>
#include<iterator>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
char num=0;
int a;
int n=3;
vector<int> res;
int left = -1, right = -1;
//cout << "输入数组:" << endl;
//n
while ((cin.peek() != EOF) && (cin.peek() != '\n'))//次数问题
{
cin >> num;
//cout << num;
if (num =='0'|| num == '1' || num == '2' || num == '3' || num == '4' ||
num == '5' || num == '6' || num == '7' || num == '8' || num == '9' )
{
//cout << num<<",";
a = num - '0';
nums.push_back(a);
}
//if (cin.get() == '\n') break;
//n--;
}
//cout << "输入和:" << endl;
cin >> target;
vector<int> cha;
for (vector<int>::iterator it=nums.begin();it!=nums.end();it++)
{
cha.push_back(target - *it);
}
for (vector<int>::iterator it = cha.begin();it != cha.end();it++)
{
int i = it - cha.begin();
for (vector<int>::iterator it1 = nums.begin();it1 != nums.end();it1++)
{
int j = it1 - nums.begin();
if (i!=j&&*it == *it1)
{
res.push_back(it-cha.begin());
res.push_back(it1-nums.begin());
return res;
}
}
}
return res;
}
};
int main()
{
Solution a;
vector<int> nums;
vector<int> res;
int target=0;
char s=0;
//cout << "输入和:" << endl;
//cin >> target;
//cin >> s;
//cout << s<<endl;
res=a.twoSum(nums,target);
//nums.push_back(5);
//nums.push_back(8);
if (res.end() > res.begin())
{
cout << "[";
vector<int>::iterator it;
for (it = res.begin();it < res.end() - 1;it++)
cout << *it << ",";
it = res.end() - 1;
cout << *it;
cout << "]" << endl;
}
else
cout << "Can't find!" << endl;
system("pause");
return 0;
}
代码2如下: