题目
Given 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.
例子
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路一
暴力解就可以了,不难看出通过双重循环就可以解决.
类似冒泡的循环条件.时间复杂度为O(n^2).
public int [] twoSum (int [] nums, int target) {
for (int i=0 ; i<nums.length-1 ; i++){
for (int j=i+1 ; j<nums.length; j++){
if (nums[i] + nums[j] == target){
return new int []{i,j};
}
}
}
throw new RuntimeException("dont exist solution" );
}
思路二
思路一时间复杂度高的原因在于每次计算出target-nums[i]后,
需要遍历数组判断是否存在.而这个遍历过程的时间复杂的为O(n).
这部分时间是可以通过一个哈希表来缩短为O(1)的.
我们只需要在一开始将所有的数值作为key.
下标做为value存在哈希表中.
然后计算target-nums[i]的值是否在哈希表中即可.时间复杂度O(n).
public int [] twoSum2(int [] nums,int target){
Map<Integer,Integer> map = new HashMap<>();
for (int i=0 ;i<nums.length ;i++)
map .put(nums[i],i);
for (int i=0 ;i<nums.length ;i++){
int sub = target - nums[i];
if (map .containsKey(sub ) && map.get(sub ) != i)
return new int[]{ i, map .get(sub ) };
}
throw new RuntimeException("dont exist solution" );
}
思路三
在思路二中我们是在一开始将所有数据都存在哈希表中.
这样就使得一开始就要遍历一次数组.
那么我们能不能节省这一部分时间而完成任务呢.
实际上是可以的.
因为我们在遍历数组的过程中.如果找到匹配项则直接return.
如果没有才会遍历下一个.也就是说.
如果当我们在循环的过程中.维护这个哈希表.
当哈希表中没有当前nums[i]对应的值可以使它相加后等于target时,
就将这个nums[i]和i维护到哈希表中.
这样可以省一次数组的遍历.时间复杂度O(n).
public int [] twoSum3(int [] nums, int target){
Map<Integer,Integer> map = new HashMap<>();
for (int i=0 ;i<nums.length ;i++){
int sub = target - nums[i];
if (map .containsKey(sub )){
return new int []{map .get(sub ), i};
}
map .put(nums[i], i);
}
throw new RuntimeException("dont exist sulution" );
}