Given an array of integers, return indices of the both numbers such that they add-to a specific target.
You may assume this each input would has exactly one solution.
Version 1:o (n^2) "Violent original Version" O (1)
classSolution(object):
def twoSum(self, nums, target):
length = len(nums)
for i in range(length):
for j in range(i+1,length)://游标后移
if nums[i]+ nums[j]== target:
return[i,j]
Version 2:O (n^2) "Brute Force enumeration function enhancement"O (1)
classSolution(object):
def twoSum(self, nums, target):
for index , item in enumerate(nums):
for past_index , past_item in enumerate(nums[index+1:],index+1):
if item + past_item == target:
return[index, past_index]
Version 3:o (n)"Two-way hash table"O (n)
classSolution(object):
def twoSum(self, nums, target):
dd = dict()
for index , value in enumerate(nums):
dd[value]= index
for index , value in enumerate(nums):
tt = target - value
if dd.has_key(tt)and dd[tt]!= index:
return[index , dd[tt]]
Version 4: O (n)"One way hash table"O (n)
Python
classSolution(object):
def twoSum(self, nums, target):
dd = dict()
for index , value in enumerate(nums):
tt = target - value
if dd.has_key(tt)and dd[tt]!= index:
return[dd[tt],index]
else:
dd[value]= index
Java
public int[] twoSum(int[] nums, int target){
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for( int i=0;i<nums.length;i++){
if(!map.containsKey(target - nums[i])){
map.put(nums[i], i );
}else{
int[] rs ={ map.get(target-nums[i]), i };
return rs;
}
}
return nums;
}
The use of 1.enumerate built-in functions (enumeration functions)---Used to traverse the index and iterate through the elements; You can receive the second parameter to specify the index starting value.
1. Both Sum "array | hash table"