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
思路一:暴力枚举,二重循环,时间复杂度为 N^2
思路二:先排序,然后循环遍历数组,对于每一个i利用二分查找 sum -i ,时间复杂度为 N*lgN.
思路三:利用Hash存储每个数的下标。时间复杂度为 O(N).
class Solution {
public:
vector<int> twoSum(vector<int> &num, int target) {
unordered_map<int, int> mapping;
vector<int> result;
for (int i = 0; i < num.size(); i++) {
mapping[num[i]] = i;
}
for (int i = 0; i < num.size(); i++) {
const int gap = target - num[i];
if (mapping.find(gap) != mapping.end() && mapping[gap] > i) {
result.push_back(i + 1);
result.push_back(mapping[gap] + 1);
break;
}
}
return result;
}
};
本文介绍了一种经典的算法问题——寻找数组中两个数相加等于特定目标值的索引。提供了三种解决思路:暴力枚举、排序加二分查找及使用哈希表的方法,并附带了一个C++实现的例子。

9536

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



