LeetCode刷了也有350题了,觉得再刷新题没有必要了,开一个新的系列,LeetCode重点题精刷。
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].
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic={}
for i,item in enumerate(nums):
if target-item not in dic:
dic[item]=i
else:
return [i,dic[target-item]]
Basically, we should maintain a map to keep tracking the elements we have already traversed, and record the index of that element.
Time complexity: O(n)
JAVA版本
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] twoSum(int[] nums, int target) {
if(nums==null || nums.length==0){
return null;
}
int[] res=new int[2];
Map<Integer,Integer>dic=new HashMap<>();
for(int i=0;i<nums.length;i++){
if(! dic.containsKey(target-nums[i])){
dic.put(nums[i],i);
}
else{
res[0]=i;
res[1]=dic.get(target-nums[i]);
}
}
return res;
}
}