题目:
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
方法1:最直观的复杂度为O(n^2),超时。
方法2:先排序,这样的话就要记下以前的索引,转换用时O(n),排序用时O(nlgn),查找用时O(n)。
struct node {
int val;
int idx;
node(){}
node(int num, int index): val(num), idx(index) {}
bool operator < (const node& other) const {
return val < other.val;
}
};
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> ans(2);
vector<node> res(numbers.size());
//O(n)
for(int i = 0; i < numbers.size(); i++)
res[i] = node(numbers[i], i+1);
//O(nlgn)
sort(res.begin(), res.end());
int begin = 0, end = numbers.size()-1;
//O(n)
while(begin < end) {
int tmp = res[begin].val + res[end].val;
if(target == tmp) {
ans[0] = min(res[begin].idx, res[end].idx);
ans[1] = max(res[begin].idx, res[end].idx);
break;
}
else if(target > tmp)
begin++;
else
end--;
}
return ans;
}
};方法3:使用哈希表(利用stl中的unordered_map实现),边建表,边判断,复杂度为最优O(n)。
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> ans(2);
int len = numbers.size();
unordered_map<int, int> hash_table;
for(int i = 0; i < len; i++) {
//表中存在与它和为target的数
int other = target - numbers[i];
if(hash_table.find(other) != hash_table.end()) {
ans[0] = hash_table[other];
ans[1] = i+1;
break;
}
//不在hash表中,加入
if(hash_table.find(numbers[i]) == hash_table.end())
hash_table[numbers[i]] = i+1;
}
return ans;
}
};
本文探讨了在整数数组中寻找两个数使它们的和等于特定目标值的问题。介绍了三种解决方案:直接双层循环、排序加双指针以及哈希表方法。哈希表方法在时间和空间效率上表现最佳。
152

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



