3Sum——leetcode
2024-10-08 00:44:26
Given an array S of n integers, are there elements a, b, c in S such that a + b + c =
0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is:
(-1, 0, 1)
(-1, -1, 2)
public class Solution {
public List<List<Integer>> threeSum(int[] num) {
Set<List<Integer>> set=new HashSet<List<Integer>>();
Arrays.sort(num);
List<List<Integer>> ans=new ArrayList<List<Integer>>();
if(num.length<=2)
{
return ans;
}
for(int i=0;i<num.length-2;i++)
{
if(i>0&&num[i]==num[i-1])
{
continue;
}
int j=i+1;
int k=num.length-1;//j,k双指针,巧妙降低复杂度至N^2
while(j<k)
{
int sum=num[i]+num[j]+num[k];
if(sum==0)
{
List<Integer> list=new ArrayList<Integer>();
list.add(num[i]);
list.add(num[j]);
list.add(num[k]);
set.add(list);
j++;k--;
}
else if(sum<0)
{
j++;
}
else
{
k--;
}
}
}
ans.addAll(set);//这个函数不错,可以把set中的元素全都添加到List。List的函数addAll(<Collection>)
return ans;
}
}
最新文章
- iOS之push present 动画
- JavaScript 中的内存泄漏
- WCF的简单
- Elasticsearch .net 客户端条件拼接查询
- VI/VIM 常用命令
- angular实现输入框输入添加 搜索框查询
- Effective Java 第三版——4. 使用私有构造方法执行非实例化
- Hibernate--对象关系
- 实例分析Vue.js中 computed和methods不同机制
- 在虚拟机中搭建qduoj(二)——安装OJ
- [C#]WinForm 中 comboBox控件之数据绑定
- spring和springmvc配置分离
- .NetCore源码阅读笔记系列之Security (三) Authentication &; AddOpenIdConnect
- Postgres 的 Range 类型
- Python实现随机读取文本N行数据
- 【Java】SAX解析characters 错误截取问题的解决
- 异常处理与MiniDump详解(3) SEH(Structured Exception Handling)
- 详解C#中的反射(转发)
- 北京Uber优步司机奖励政策(10月12日~10月18日)
- oracle 查看一个表中的记录是否被锁住
热门文章
- XPath函数——字符串函数(转载)
- python学习笔记-(十五)RabbitMQ队列
- nginx 499 状态码优化
- log4j日志工具
- 深入理解javascript原型和闭包(5)——instanceof
- 用类方法------>;快速创建一个autorelease的对象,在封装的类方法内部
- There are no resources that can be added or removed from the server
- PHP大数(浮点数)取余
- Java NIO工作原理
- BZOJ 4581: [Usaco2016 Open]Field Reduction