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 eGiven 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].
解法一:双层循环 o(n^2)
1.返回条件跳出双层循环 2时间复杂度 3.明天继续优化
//Runtime: 58 ms 2016-8-16 22:06:09
public static int[] twoSum(int[] nums, int target) {
//两次遍历 时间复杂度 n*n
int[] result = new int[2];
int len= nums.length;
for(int i =0;i<len;i++){
for(int j=i+1;j<len;j++){
if(target==nums[i]+nums[j]){
result[0]=i;
result[1]=j;
return result;
}
}
}
return result;
}
-----------------------------------------------------second edit time 2016-8-18 21:05:22-----------------------------------------------------------------------------------
解法二:hash方法 o(n)
public static int[] twoSum_Hash_error(int[] nums, int target){
int[] result = new int[2];
HashMap<Integer, Integer> map= new HashMap<Integer, Integer>();
int len=nums.length;
for(int i=0;i<len;i++){
map.put(nums[i],i);
}
for(int i=0;i<len;i++){
if(map.containsKey(target-nums[i])){
result[1]=i;
result[0]=map.get(target-nums[i]);
return result;
}
}
return result;
}
错误原因:
2.2正确hash解法:
//Runtime: 6 ms o(n) 空间 o(n)
public static int[] twoSum_Hash(int[] nums, int target){
int[] result = new int[2];
HashMap<Integer, Integer> map= new HashMap<Integer, Integer>();
int len=nums.length;
for(int i=0;i<len;i++){
if(map.containsKey(target-nums[i])){
result[1]=i;
result[0]=map.get(target-nums[i]);
return result;
}else{
map.put(nums[i],i);
}
}
return result;
}
在一个for循环中,如果target- nums[ i] 不在map中,则存入map中,避免错误1。