Question:
Given an array of integers, returnIndicesOf the two numbers such that they add up to a specific target.
You may assume that each input wocould haveExactlyOne solution.
Example:
Given Nums = [2, 7, 11, 15], target = 9,
Because Nums [0] + Nums [1] = 2 + 7 = 9,
Return [0, 1].
Method:
Java
- 1. Dual-cycle of violence, time complexity is O (n ^ 2)
publicclassSolution{
publicint[] twoSum(int[] nums,int target){
int[] arr =newint[2];
for(int i =0;i< nums.length-1; i++){
for(int j = i+1; j< nums.length; j++){
if(target == nums[i]+ nums[j]){
arr[0]= i ;
arr[1]= j ;
}
}
}
return arr ;
}
}
- 2. With hashmap or hashtable, the time complexity is O (n)
publicclassSolution{
publicint[] twoSum(int[] nums,int target){
int[] result ={0,0};
Map<Integer,Integer> map =newHashMap<Integer,Integer>();
for(int i =0;i<nums.length;i++){
if(map.containsKey(target-nums[i])){
result[0]= map.get(target-nums[i]);
result[1]= i;
}else{
map.put(nums[i],i);
}
}
return result ;
}
}
Analysis of ideas:
Obviously better than the first solution, greatly reducing the time complexity
Create a hash table and use the array's V value and index value as the K-V of the hash table
When target-K exists in the table, the corresponding value is taken out, which is the location to be searched.
Python
The same hashtable idea, key is number, value is Index
classSolution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
index ={};
for i,j in enumerate(nums):
if target-j in index:
return[index[target-j],i]
index[j]= i
From Weizhi note (wiz)
[Leetcode 001] Two sum