题目:
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
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
解题思路:两个for语句循环,找到相加等于target值,然后定义一个容器接收这两个值,函数返回容器,但是O(n^2)的时间复杂度,AC不了。。。。代码如下:
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
vector<int> twoSum(vector<int> &numbers, int target)
{
vector<int> sum;
for (int i = 0; i != numbers.size(); i++)
{
for (int j = i + 1; j != numbers.size(); j++)
{
if (numbers[i] + numbers[j] == target)
{
sum.push_back(i + 1);
sum.push_back(j + 1);
break;
}
}
}
return sum;
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> s{2,7,11,13};
vector<int> s2 = twoSum(s, 9);
for (int i = 0; i <s2.size(); ++i)
cout << s2[i] << endl;
return 0;
}