overview
题目
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
暴力
遍历每种组合,只有一个答案,则找到即可。
class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
int[] r = new int[2];
for(int i=0;i<len;i++){
for(int j= i+1;j<len;j++){
if(nums[i]+nums[j]==target){
r[0] =i;
r[1] =j;
return r;
}
}
}
return r;
}
}
执行用时: 52 ms
内存消耗: 38.8 MB
hashmap
双层循环是为了找到与自己匹配的另一个数,但时间复杂度较大,优化的角度可以考虑以空间换时间。
我想到是对数组排序后,用双指针,从两端搜索。但要输出index,排序后不太行。
提示中给出了hashmap的方法,通过map来快速查找。是对匹配(查找)过程的改进,暴力中是通过遍历去查找,用map代替遍历查找后,实现了从O(n)到 O(1)的查找,所以能明显的提速。
class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
Map<Integer,Integer> map = new HashMap();// map need Intergder
int other = 0;
for(int i=0;i<len;i++){
other = nums[i];
if(map.containsKey(other)){// functuion name 驼峰命令
return new int[] {i,map.get(other)}; // how to new int[]
}
map.put(target-other,i);// cancel "else" will quick
}
return null; // !!!
}
}
执行用时: 1 ms
内存消耗: 38.6 MB
测评结果有些出乎意料北,时间显著减少,但内存无明显变化,可能和JVM有关?
编码改进
上述代码有多个return,使得代码结构较为复杂,稍微对逻辑进行修改,使得代码更便于理解
//import java.util.Arrays;
class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
Map<Integer,Integer> map = new HashMap();
int other = 0;
int[] r = new int[2];
for(int i=0;i<len;i++){
other = nums[i];
if(map.containsKey(other)){// functuion name xxXxx
//return new int[] {i,map.get(other)};// map need Intergder // how to new int[]
r[0]=i;
r[1]=map.get(other);
break;
}
map.put(target-other,i);// cancel "else" will quick
}
return r; // !!!
}
}
执行用时: 1 ms
内存消耗: 38.7 MB
思考
题中只有一个答案,如果存在多个答案,情况会略复杂。
首先是返回值是一个二维数组,包含若干对结果对。除此之外,对算法本身修改较小,只需要完整遍历即可。