四数之和
题目链接: leetcode18
题目描述
解题思路
本题是三数之和的扩展版本,但是与三数之和不同之处在于,本题是指定了目标值,我们拿到题目第一步还是先对题目给定的数组做排序。然后我们通过for循环对开始确定四数之和的第一个数,和三数之和的逻辑相同我们先对于数据进行去重复与剪枝。剪枝后进行三数之和的操作。
代码
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> arrayList = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
if (nums[i] > target && nums[i] > 0){
return arrayList;
}
if (i > 0 && nums[i] == nums[i - 1]){
continue;
}
for (int k = i+1; k < nums.length; k++) {
if(k > i+1 && nums[k]==nums[k-1]){
continue;
}
int left = k+1;
int right = nums.length - 1;
while (left < right){
long res = (long)nums[i] + nums[k] + nums[left] + nums[right];
if (res > target){
right--;
}else if (res < target){
left++;
}else {
arrayList.add(Arrays.asList(nums[i],nums[k],nums[left],nums[right]));
while (left < right && nums[left] == nums[left+1]){left++;}
while (left < right && nums[right] == nums[right-1]){right--;}
left++;
right--;
}
}
}
}
return arrayList;
}
}
提交
参考
https://leetcode.cn/problems/4sum/submissions/
https://programmercarl.com/0018.%E5%9B%9B%E6%95%B0%E4%B9%8B%E5%92%8C.html#%E5%85%B6%E4%BB%96%E8%AF%AD%E8%A8%80%E7%89%88%E6%9C%AC