Last active
July 27, 2017 23:56
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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