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
题目意思是:给定一个数组,给一个数target,在数组找到两个数的和为target,找出这个两个数的位置,其下标索引从1开始算起。
思路:
方法一:暴利求,两个for循环遍历,找到退出,复杂度O(n2)
方法二::hash 用一个哈希表,存储每个数对应的下标,复杂度 O(n).
方法二解答:
class Solution
{
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
unordered_map<int, int> mapping;
vector<int> result;
for (int i = 0; i < numbers.size(); ++i)
{
mapping[numbers[i]] = i;
}
for (int i = 0; i < numbers.size(); ++i)
{
const int tmp = target - numbers[i];
if (mapping.find(tmp) != mapping.end() && mapping[tmp]>i)
{
result.push_back(i+1);
result.push_back(mapping[tmp] + 1);
break;
}
}
return result;
}
}; 在线推送结果为:
Question:
Similar to Question [1. Two Sum], except that the input array is already sorted in
ascending order.
问题:假如数组是有序的话我们就可以同时从头尾开始向中遍历。
class Solution
{
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
vector<int> result;
int i = 0;
int j = numbers.size() - 1;
while (i < j)
{
int sum = numbers[i] + numbers[j];
if (sum < target)
++i;
else if (sum>target)
--j;
else
{
result.push_back(i + 1);
result.push_back(j + 1);
break;
}
}
return result;
}
};
本文介绍了一种在已排序数组中寻找两数之和等于特定目标值的有效算法。通过从数组两端开始向中间搜索的方法,可在O(n)的时间复杂度内解决问题。
2万+

被折叠的 条评论
为什么被折叠?



