Two Sum
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Python:
#coding:utf-8
class Solution:
def twoSum(self,list1,target):
if len(list1)<0:
return false
end=[]
subdict={}
for i in range(len(list1)):
if list1[i] in subdict:
end.append([subdict[list1[i]],i])
else:
subdict[target-list1[i]]=i
return end
if __name__=="__main__":
list1=[1,2,3,4]
target=5
print Solution().twoSum(list1,target)
Java:
java:
public int[] twoSum(int[],numbers,int target){
int[] result=new int[2];
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<numbers.length;i++){
if(map.containsKey(target-numbers[i])){
reult[0]=map.get(target-numbers[i]);
result[1]=i;
}
else{
map.put(numbers[i]);
}
}
return result;
}