Skip to content

Instantly share code, notes, and snippets.

@BiruLyu
Last active July 27, 2017 23:56
Show Gist options
  • Save BiruLyu/14c31c1f01f0ab6c875b497ff2c7e97c to your computer and use it in GitHub Desktop.
Save BiruLyu/14c31c1f01f0ab6c875b497ff2c7e97c to your computer and use it in GitHub Desktop.
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
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;
}
}
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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment