本例代码下载地址:TwoSum下载
题目描述:
简单地说就是给出一个数字和一个目标数,求数组中符合目标数的任意2个数(不包括自身)在数组中的下标。
解决思路:
常规做法是for循环,通过第一个数值(比如下标为0,1,2……)与剩下数值比对,符合条件的即为答案。时间复杂度为O(n^2)。
代码如下:
public int[] twoSum(int[] nums, int target) {
if (nums.length < 2){
return null;
}
int[] result = null;
for (int i = 0; i < nums.length; i++){
for (int j = i + 1; j < nums.length; j++){
if (nums[i] + nums[j] == target){
result = new int[2];
result[0] = i;
result[1] = j;
break;
}
}
}
return result;
}
改进:
我们常说的可以用空间换时间的方式来降低时间复杂度,那么在本例中可不可以呢?
答案是可以的。我们用map来储存用过的数字,这样当target - 当前值 = map中存在的数字时,即可认为储存的数字 = 第一个下标,当前的数字 = 第二个下标。算法复杂度0(n)。文字比较抽象,可以看下图来帮助理解:
代码实现:
public static int[] twoSumImprove(int[] nums, int target){
if (nums.length < 2){
return null;
}
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] result = null;
for (int i = 0; i < nums.length; ++i) {
if (map.containsKey(target - nums[i])) {
result = new int[2];
result[0] = map.get(target - nums[i]);
result[1] = i;
break;
}
// 将比较过的数加入map
map.put(nums[i], i);
}
return result;
}