class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
buffer_dict = {}; #Use a dictionary to store the valur target - nums[i],the time complexity is O(n)
for i in range(len(nums)):
if nums[i] in buffer_dict:
return [buffer_dict[nums[i]], i];
else:
buffer_dict[target - nums[i]] = i;
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> bufferMap = new HashMap<Integer,Integer>();
int[] res = new int[2];
for(int i = 0; i< nums.length; i++){
if(bufferMap.containsKey(nums[i])){
res[0] = bufferMap.get(nums[i]);
res[1] = i;
return res;
}
bufferMap.put(target - nums[i],i);
}
return res;
}
}