三数之和
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
分析:
暴力法
O
(
n
3
)
O(n^3)
O(n3),必然不能满足要求,考虑利用之前求两数之和的方法(两指针法),迁移到三数之和上。
/*
对数组排序,选择一个C位出道的元素nums[i],从剩下的元素中找出两个和nums[i]的和为0,
这两个元素的寻找过程可以参照求两数之和的方法
时间O(n^2),空间O(1)
*/
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList();
int len = nums.length;
for(int i = 0; i < len; i++){
//因为排序过了,大于0则三个数之和不可能为0
if(nums[i] > 0) break;
//重复的C位出道元素
if(i > 0 && nums[i] == nums[i-1]) continue;
int left = i+1;
int right = len - 1;
while(left < right){
int temp = nums[i] + nums[left] + nums[right];
//三个数之和确实为0,则添加到List中
if(temp == 0){
res.add(Arrays.asList(nums[i],nums[left], nums[right]));
//重复元素情况
while(left < right && nums[left] == nums[left+1]){
left++;
}
while(left < right && nums[right] == nums[right-1]){
right--;
}
left++;
right--;
}else if(temp < 0){
left++;
}else if(temp > 0){
right--;
}
}
}
return res;
}
}
四数之和
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
分析
思路和三个数之和类似,时间
O
(
n
3
)
O(n^3)
O(n3),空间O(1)
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList();
int len = nums.length;
for(int i = 0; i < len-1; i++){
//排除第一个C位重复元素(重复元素造成结果有重复的,因此排除)
if(i>0 && nums[i] == nums[i-1]) continue;
for(int j = i+1; j < len; j++){
//排除第二个C未重复元素
if(j > i+1 && nums[j] == nums[j-1]) continue;
int left = j+1;
int right = len-1;
while(left < right){
int temp = nums[i] + nums[j] + nums[left] + nums[right];
if(temp == target){
res.add(Arrays.asList(nums[i],nums[j], nums[left],nums[right]));
//排除剩余的重复元素
while(left < right && nums[left] == nums[left+1]) left++;
while(left < right && nums[right] == nums[right-1]) right--;
left++;
right--;
}else if(temp < target){
left++;
}else if(temp > target){
right--;
}
}
}
}
return res;
}
}