博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode--018--四数之和(java)
阅读量:4445 次
发布时间:2019-06-07

本文共 1476 字,大约阅读时间需要 4 分钟。

给定一个包含 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]] 和三数之和的区别就是,在外层多了一层for循环。
class Solution {    public List
> fourSum(int[] nums, int target) { List
> res = new ArrayList<>(); if(nums.length < 4)return res; Arrays.sort(nums); for(int i = 0;i < nums.length - 3;i++){ if(i > 0 && nums[i] == nums[i-1])continue; for(int j = i + 1;j < nums.length - 2;j++){ if(j > i + 1 && nums[j] == nums[j-1]) continue; int low = j + 1,high = nums.length - 1; while(low < high){ int sum = nums[i] + nums[j] + nums[low] + nums[high]; if(sum == target){ res.add(Arrays.asList(nums[i],nums[j],nums[low],nums[high])); while(low < high && nums[low] == nums[low+1])low++; while(low < high && nums[high] == nums[high-1]) high--; low++; high--; }else if(sum < target){ low++; }else high--; } } } return res; }}

2019-04-17 21:23:25

 

转载于:https://www.cnblogs.com/NPC-assange/p/10726298.html

你可能感兴趣的文章
结对博客
查看>>
我在城市快节奏中的慢生活
查看>>
B1232 [Usaco2008Nov]安慰奶牛cheer 最小生成树
查看>>
使用 git push 出现error setting certificate verify locations问题记录
查看>>
真没想到VB也可以这样用之指针技术 --不详,向作者致敬  ,转
查看>>
2、在1.VMware虚拟机上安装ubantu系统
查看>>
vue
查看>>
用 eric6 与 PyQt5 实现python的极速GUI编程(系列01)--Hello world!
查看>>
java--线程的睡眠sleep()
查看>>
Python3.x:定时获取页面数据存入数据库
查看>>
洛谷 P1290 欧几里德的游戏 题解
查看>>
python 归纳 (十三)_队列Queue在多线程中使用
查看>>
idea管理tomcat
查看>>
System.Activator类
查看>>
ssis包
查看>>
Python的静态方法和类成员方法 分类: python基础学习 ...
查看>>
黑马程序员_java基础笔记(01)...java的环境搭建
查看>>
oracle创建表空间并对用户赋权
查看>>
seajs-require使用示例
查看>>
MediaElement视频控制:播放、暂停、停止、后退、快进、跳转、音量
查看>>