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].
在给出的列表找查找是否存在一个数,满足:target-nums[1]。实际上还有个类似的题目,叫three sums。只是两个数变成了三个数,解决思路类似。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
for (int i = 0; i != nums.size(); i++)
{
for (int j = i + 1; j != nums.size(); j++)
{
if ((target - nums[i]) == nums[j])
{
result.push_back(i);
result.push_back(j);
}
}
}
return result;
}
};
#include<iostream>
#include<stdlib.h>
#include<algorithm>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
for (int i = 0; i != nums.size(); i++)
{
for (int j = i + 1; j != nums.size(); j++)
{
if ((target - nums[i]) == nums[j])
{
result.push_back(i);
result.push_back(j);
}
else
cout << i <<" "<<"and"<<" "<< j <<" "<< "both are not the targets!" << endl;
}
}
cout << "Here are the correct numbers:" << endl;
for (int i = 0; i < result.size(); i++)
{
cout << result[i] << endl;
}
return result;
}
};
int main(void)
{
Solution s;
vector<int> test;
test.push_back(3);
test.push_back(2);
test.push_back(4);
vector<int>::iterator it;
cout << "Here are test array:" << endl;
for (it = test.begin(); it != test.end(); it++)
{
cout << *it << " ";
}
cout << endl;
s.twoSum(test,6);
system("pause");
return 0;
}