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].
Python:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# for i in range(len(nums)): ##O(n2)time
# for j in range(i+1,len(nums)):
# if nums[i] + nums[j] == target:
# return [i,j]
if len(nums) < 1: ##O(n)time
return False
dictt = {}
for i in range(len(nums)):
if nums[i] in dictt:
return [dictt[nums[i]],i]
else:
dictt[target - nums[i]] = i ## 若输出为[i,j]
## dictt中的key值为target-nums[i],value值为i
C++:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> dictt;
vector<int> result;
for(int i = 0; i < nums.size(); ++i){
int numbertofind = target - nums[i];
if(dictt.find(numbertofind) != dictt.end()){
result.push_back(dictt[numbertofind]);
result.push_back(i);
}
else{
dictt[nums[i]] = i;
}
}
return result;
}
};