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
一开始暴力解决,导致超时。后来自己写了个快速排序的算法,先对数据进行排序,发现还是超时。
后来发现,在LeetCode中可以直接使用C++ STL的一些容器,所以题目很容易就AC了。
以下是暴力方法:
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
int notfound = 1, i, j;
for(i = 0; i < numbers.size() && notfound; ++i)
for(j = i+1; j < numbers.size(); ++j)
if(numbers[i] + numbers[j] == target)
{
notfound = 0;
break;
}
vector<int> ret;
ret.push_back(i+1);
ret.push_back(j+1);
return ret;
}
};
下面的算法用map保存输入的数据,map会自动将数据排序,由于题目指出“ You may assume that each input would have exactly one solution.”由此可以判断出输入的数据里面不会有重复的,那么用map的时候不用考虑重复的情况。
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
map<int, int> mp;
for(int i = 0; i < numbers.size(); ++i)
mp[numbers[i]] = i + 1;
for(int i = 0; i < numbers.size(); ++i)
{
int b = target - numbers[i];
int j = mp[b];
if(j > 0 && i + 1 != j)
{
vector<int> ret;
ret.push_back(i+1);
ret.push_back(j);
return ret;
}
}
}
};