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;
}
}

最新文章

  1. iOS之push present 动画
  2. JavaScript 中的内存泄漏
  3. WCF的简单
  4. Elasticsearch .net 客户端条件拼接查询
  5. VI/VIM 常用命令
  6. angular实现输入框输入添加 搜索框查询
  7. Effective Java 第三版——4. 使用私有构造方法执行非实例化
  8. Hibernate--对象关系
  9. 实例分析Vue.js中 computed和methods不同机制
  10. 在虚拟机中搭建qduoj(二)——安装OJ
  11. [C#]WinForm 中 comboBox控件之数据绑定
  12. spring和springmvc配置分离
  13. .NetCore源码阅读笔记系列之Security (三) Authentication &amp; AddOpenIdConnect
  14. Postgres 的 Range 类型
  15. Python实现随机读取文本N行数据
  16. 【Java】SAX解析characters 错误截取问题的解决
  17. 异常处理与MiniDump详解(3) SEH(Structured Exception Handling)
  18. 详解C#中的反射(转发)
  19. 北京Uber优步司机奖励政策(10月12日~10月18日)
  20. oracle 查看一个表中的记录是否被锁住

热门文章

  1. XPath函数——字符串函数(转载)
  2. python学习笔记-(十五)RabbitMQ队列
  3. nginx 499 状态码优化
  4. log4j日志工具
  5. 深入理解javascript原型和闭包(5)——instanceof
  6. 用类方法------&gt;快速创建一个autorelease的对象,在封装的类方法内部
  7. There are no resources that can be added or removed from the server
  8. PHP大数(浮点数)取余
  9. Java NIO工作原理
  10. BZOJ 4581: [Usaco2016 Open]Field Reduction