目录
两数之和
https://leetcode-cn.com/problems/two-sum/
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
java 实现
方法一:一遍hash表 解法
思路
标签:哈希映射
- 这道题本身如果通过暴力遍历的话也是很容易解决的,时间复杂度在 O(n2)
- 由于哈希查找的时间复杂度为 O(1),所以可以利用哈希容器 map 降低时间复杂度
- 遍历数组 nums,i 为当前下标,每个值都判断map中是否存在 target-nums[i] 的 key 值
- 如果存在则找到了两个值,如果不存在则将当前的 (nums[i],i) 存入 map 中,继续遍历直到找到为止
- 如果最终都没有结果则抛出异常
时间复杂度:O(n)
/**
* 一遍hash 表
* 事实证明,我们可以一次完成。在进行迭代并将元素插入到表中的同时,
* 我们还会回过头来检查表中是否已经存在当前元素所对应的目标元素。
* 如果它存在,那我们已经找到了对应解,并立即将其返回
*/
public int[] twoSum(int[] nums, int target) { //一遍hash表
Map<Integer, Integer> map = new HashMap<>();
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
int num = target - nums[i];
if (map.containsKey(num)) {
return new int[]{map.get(num), i};
}
map.put(nums[i], i);
}
return result;
}
方法二:暴力法
暴力法很简单,遍历每个元素 xx,并查找是否存在一个值与 target - xtarget−x 相等的目标元素。
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
复杂度分析:时间复杂度:O(n^2) 、空间复杂度:O(1)
对于每个元素,我们试图通过遍历数组的其余部分来寻找它所对应的目标元素,这将耗费 O(n) 的时间。因此时间复杂度为 O(n^2)。
三数之和
题目:
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 :
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
解法一、排序+双指针
思路
- 首先对数组进行排序,排序后固定一个数nums[i],再使用左右指针指向 nums[i]后面的两端,数字分别为 nums[L和 nums[R],计算三个数的和 sum 判断是否满足为0,满足则添加进结果集
- 如果nums[i]大于0,则三数之和必然无法等于 0,结束循环
- 如果 nums[i] ==nums[i−1],则说明该数字重复,会导致结果重复,所以应该跳过
- 当 sum == 0 时,nums[L] == nums[L+1] 则会导致结果重复,应该跳过,L++
- 当 sum== 00 时nums[R] ==nums[R−1] 则会导致结果重复,应该跳过,R--
时间复杂度:O(n^2)
代码:
class Solution {
public List<List<Integer>> threeSum(int[] nums) { // 双指针解法
Arrays.sort(nums); //先进行排序
List<List<Integer>> result = new ArrayList();
for (int i= 0; i< nums.length -2 ; i ++) {
int head = i+ 1, tail = nums.length -1;//双指针
if (nums[i]> 0 ) break; //说明所有值都大于0
if (i> 0 && nums[i]==nums[i-1]) continue;//去重复的,当值相等时候退出此次循环
while (head< tail) {
int sum = nums[i] + nums[head] + nums[tail];
if (sum < 0) { //如果小于0 左指针需要移动
head ++;
}
if (sum > 0) { //如果大于0 右指针需要移动
tail --;
}
if ( sum == 0) {
result.add(Arrays.asList(nums[i],nums[head],nums[tail]));
head ++ ;
tail --;
while (head< tail && nums[head]==nums[head-1]) head ++;//去重复的
while (head< tail && nums[tail]==nums[tail+1]) tail --;//去重复的
}
}
}
return result;
}
}