给定一个整数数组 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 <= 104-109 <= nums[i] <= 109-109 <= target <= 109- 只会存在一个有效答案
常规做法:
通过枚举,遍历所有种可能性,复杂度为O(n2).
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
for (int i = 0 ; i < n ; i++) {
for (int j = i + 1 ; j < n ; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return null;
}
哈希表做法:
使用hash表,用空间换时间,复杂度O(n).
通过hash表记录之前出现过的数字,判断枚举的num值相加是否可以满足等于target。
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hash = new HashMap<>();
for (int i = 0 ; i < nums.length ; i++) {
int difference = target - nums[i];
if (hash.get(difference) != null) {
return new int[]{hash.get(difference), i};
}
hash.put(nums[i], i);
}
return null;
}
进阶做法:
利用概率性,从两边往中间同时找 比 同一侧找单独找匹配的概率更高,因为结果为随机分布,同时比单独找概率高两倍。
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hash = new HashMap<>();
int n = nums.length;
for (int i = 0, j = n - 1 ; i <= j ; i++, j--) {
int difference = target - nums[i];
if (nums[i] + nums[j] == target && i != j) {
return new int[]{i, j};
}
if (hash.get(difference) != null) {
return new int[]{hash.get(difference), i};
}
difference = target - nums[j];
if (hash.get(difference) != null) {
return new int[]{hash.get(difference), j};
}
hash.put(nums[i], i);
hash.put(nums[j], j);
}
return null;
}
No responses yet