题目:
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
提示:
2 <= nums.length <= 10^4
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9
只会存在一个有效答案
进阶:你可以想出一个时间复杂度小于 O(n2) 的算法吗?
暴力
/**
* 思路:
* 遍历所有可能
*/
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for (int i=0;i<nums.length-1;i++){
for (int j=i+1;j<nums.length;j++){
if (nums[i]+nums[j]==target){
result[0]=i;
result[1]=j;
return result;
}
}
}
return result;
}
时间复杂度:On^2
空间复杂度:O1
hash
两次hash
/**
* 思路:
* 将(值,下标)存入map
* 遍历数组,查看当前值需要的那个数是否在map中存在
* 如果存在,同时要判断下标是否相同
*
* 特殊值:{3,3}{3,2,4}
* 这里巧妙的应用的一点:
* 我们在map中put数据的时候,即使key重复,
* 我们记录的value也是后面的下标,而我们进行第二次遍历的时候的从前往后去寻找
*/
public static int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int need = target - nums[i];
if (map.containsKey(need) && map.get(need)!=i ) {
result[0] = i;
result[1] = map.get(need);
return result;
}
}
return result;
}
时间复杂度:On
空间复杂度:On
一次hash
/**
* 思路:
* 遍历数组,查看map中是否有需要的数,没有就把当前的数放入map
* 因为答案只有一个,有需要的数便可立即返回
*/
public static int[] twoSum2(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
int need = target - nums[i];
if (map.containsKey(need)) {
result[0] = i;
result[1] = map.get(need);
return result;
}
map.put(nums[i], i);
}
return result;
}
时间复杂度:On
空间复杂度:On