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].
算法:
In the first iteration, we add each element's value and its index to the table. Then, in the second iteration we check if each element's complement (target - nums[i]target−nums[i]) exists in the table. Beware that the complement must not be nums[i]nums[i] itself!
While we iterate and inserting elements into the table, we also look back to check if current element's complement already exists in the table. If it exists, we have found a solution and return immediately.
设存在着一对解m, n,设m在序列中排在n的前面。从头到尾遍历该序列,用数据结构S存储已经遍历过的数据。遍历到m时候,寻找target-m是否在S中,这时候还是不在。但是遍历到n的时候就发现target-n,也就是m,在S中,这时候我们就得到了解。该方法的时间复杂度为O(n),但是可能需要额外O(n)的存储空间。而数据结构要很方便于查询,所以可使用字典(C++中用map,Python中用dict,存储数据以及下标),查询复杂度为O(1)。
注意点在于map的索引是给定nums值,存放的数据是下标。
比如给3,2,4,Target为6。设map为空,当第一迭代,i=1取到3时,6-3=3不在map中,将3存为索引,1存为3对应的值。当第二迭代,i=2取到2时,6-2=4不在map中,将2存为索引,2存为2对应的值。当第三次迭代,i=3取到4时,6-4=2在map中,返回i和map中索引为6-4=2的数值。
python:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
tmp_num = {}
for i in range(len(nums)):
if target - nums[i] in tmp_nums:
return (tmp_num[starget-nums[i]], i)
else:
tmp_num[nums[i]] = i
return (-1, -1)
C++:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> searched;
vector<int> res;
for (int i = 0; i < nums.size(); ++i){
if (searched.count(target - nums[i])){
res.push_back(searched[target - nums[i]]);
res.push_back(i);
return res;
} else {
searched[nums[i]] = i;
}
}
res.push_back(-1);
res.push_back(-1);
return res;
}
};
java:
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}