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].
Java
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> lookup= new HashMap<>();
for (int i = 0; i < nums.length; ++i){
int diff = target - nums[i];
if(lookup.get(diff) != null){
return new int[]{lookup.get(diff), i};
} else {
lookup.put(nums[i], i);
}
}
return null;
}
}
Python
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lookup = {}
for idx, num in enumerate(nums):
if target - num in lookup:
return [lookup[target - num], idx]
lookup[num] = idx