leetcode - two-sum
Q
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
- 1
- 2
- 3
- 4
- 5
A - 1 暴力破解
枚举数组中的每一个数 x,寻找数组中是否存在 target - x
使用遍历整个数组的方式寻找 target - x 时,需要注意到每一个位于 x 之前的元素都已经和 x 匹配过,因此不需要再进行匹配。
而每一个元素不能被使用两次,所以我们只需要在 x 后面的元素中寻找 target - x。
public class TwoSum {
public static int[] twoSum(int[] nums, int target) {
int len = nums.length ;
for (int i = 0; i < len; i++) {
for (int j = i+1 ; j < len ; j++){
if (nums[i] + nums[j] == target){
return new int[]{i,j};
}
}
}
return new int[0];
}
public static void main(String[] args) {
int[] nums = new int[]{1,3,4,2};
int target = 6;
int[] targetArr = twoSum(nums, target);
System.out.println(targetArr[0]);
System.out.println(targetArr[1]);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
复杂度分析
时间复杂度:O(N^2),其中 N 是数组中的元素数量。最坏情况下数组中任意两个数都要被匹配一次。
空间复杂度:O(1) ,只用到了常数个变量
Q -2 查找表法
上面暴力破解的方法我们也看到了,时间复杂度 O(N^2) , 如何优化呢?
通常都是使用 空间换时间
比如我们在遍历的同时,去记录一些信息,为了是去掉一层循环。 那如果要记录已经遍历的数值和它对应的下标, 可以借助查找表发来实现。
常用的查找表的两个实现是
- 哈希表
- 平衡二叉搜索树
因为这里没有排序的需求,所以使用哈希表即可。
public static int[] twoSum2(int[] nums, int target) {
int len = nums.length;
Map<Integer, Integer> map = new HashMap<Integer, Integer>(len - 1);
for (int i = 0; i < len; i++) {
int another = target - nums[i] ;
if (map.containsKey(another)){
return new int[]{map.get(another),i};
}
map.put(nums[i], i);
}
return new int[0];
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
遍历数组 nums,i 为当前下标,每个值都判断map中是否存在 target-nums[i] 的 key 值;
如果存在则找到了两个值,如果不存在则将当前的 (nums[i],i) 存入 map 中,继续遍历直到找到为止
复杂度分析
时间复杂度:O(N),其中 NN 是数组中的元素数量。对于每一个元素 x,我们可以 O(1)地寻找 target - x。
空间复杂度:O(N),其中 NN 是数组中的元素数量。主要为哈希表的开销。
文章来源: artisan.blog.csdn.net,作者:小小工匠,版权归原作者所有,如需转载,请联系作者。
原文链接:artisan.blog.csdn.net/article/details/111501280
- 点赞
- 收藏
- 关注作者
评论(0)