首页 技术 正文
技术 2022年11月15日
0 收藏 430 点赞 4,772 浏览 1020 个字

18. 四数之和

给定一个包含 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]

]

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/4sum

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
int len = nums.length;
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(nums.length<4) return res;
Arrays.sort(nums);
if(nums[0]>target/4 || nums[len-1]<target/4) return res;
for(int i = 0;i<len;i++){
if(nums[i]>target/4) break;
if(i>0 && nums[i]==nums[i-1]) continue;
int sum = target-nums[i];
for(int j = i+1;j<len;j++){
if(nums[j]>sum/3) break;
if(j>i+1 && nums[j]==nums[j-1]) continue;
int l = j+1;
int r = len-1;
while(l<r){
if(nums[r]<sum/3) break;
int temp = nums[j] + nums[l] +nums[r];
if(temp == sum){
res.add(Arrays.asList(nums[i],nums[j],nums[l],nums[r]));
while(l<r && nums[l] == nums[l+1]) l++;
while(l<r && nums[r] == nums[r-1]) r--;
l++;
r--;
}else if(temp>sum){//结果大了右指针往左
r--;
}else{//结果小了左指针往右
l++;
}
}
}
}
return res;
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,564
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,412
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,185
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905