Leetcode 1 Two Sum
题目描述
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
本题思路
思路1:采用暴力法,二重循环搞定。时间复杂度为o(n^2),空间复杂度为o(1)。
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res; for (int i=0; i<nums.size(); ++i) { for(int j=0; j != i && j<nums.size(); ++j) { if (nums[i] + nums[j] == target) { res.push_back(i); res.push_back(j); return res; } } } } };
思路2:先排序,然后采用对撞指针的方式,left=0, right = nums.size() - 1。然后根据数值逐渐挪动左右指针,直至找到合适的值。然后再根据正确的值在原数组的索引。时间复杂度为o(nlgn + n),即为o(nlgn),空间复杂度为o(1)。
思路3:首先构建一个哈希表。遍历数组,如果该元素对应的target - nums[i]存在哈希表中,则直接返回结果,否则把k = nums[i], v = i 添加到哈希表中。
具体代码如下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashmap;
unordered_map<int, int>::iterator it;
vector<int> ans;
for(int i=0; i<nums.size(); ++i) {
it = hashmap.find(target - nums[i]);
if (it == hashmap.end()) {
hashmap.insert(make_pair(nums[i], i));
}
else {
ans.push_back(i);
ans.push_back(it->second);
return ans;
}
}
}
};
如果将unordered_map修改为map,运行时间则从4ms升至为8ms。

浙公网安备 33010602011771号