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: 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] ]

分析:

暴力法,三层for循环,时间复杂度为O(n^3),,这显然不是一种好的解决方式

我的做法是先对数组进行排序,这样负数在排在前面(负数越小,则它的绝对值越大),0在中间(如果存在0),正数在后面。排序算法的时间复杂度是O(nlgn)

然后从左往右取负数,从右往左取正数。即从两边向中间扫描。两个数求和的情况则刚好可以两边各取一个数进行判断,对于三个数求和的情况,我们可以先确定一个数,然后再去两个数的和为第一个取出的数的相反数即可。

注:当数组长度小于3时,直接返回null

public List<List<Integer>> func(int[] num) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
int len = num.length;
if(num==null || len<3){
return null;
}
Arrays.sort(num); for(int i =0;i<len-2;i++){
if(i>0 && num[i] == num[i-1]){
continue;
}
int j = i+1;
int k = len-1;
int target = -num[i];
while(j<k){
if(num[j]+num[k]==target){
result.add(Arrays.asList(num[i],num[j],num[k]));
j++;
k--;
while(j<k && num[j]==num[j-1]){
j++;
}
while(j>k && num[k]==num[k+1]){
k--;
}
}else if(num[j]+num[k]>target){
k--;
}else{
j++;
}
}
}
return result; }

最新文章

  1. NAT123内网映射端口
  2. C# dynamic
  3. 【HDU1538】A Puzzle for Pirates(经典的海盗问题)
  4. 数据结构(二维线段树,差分): NOI2012 魔幻棋盘
  5. UIGestureRecognizer手势
  6. cf C. Quiz
  7. 修改index.php 清空mylog1.txt
  8. Vuex随笔
  9. zeroc
  10. SQLServer之创建全文索引
  11. 【BZOJ5496】[十二省联考2019]字符串问题(后缀树)
  12. 【Teradata】磁盘碎片整理(ferret工具)
  13. @RequestMapping 和 @GetMapping @PostMapping 区别
  14. delete method not allowed 405错误
  15. AGC014E Blue and Red Tree
  16. HTML5之viewport使用
  17. 牛气冲天的Iframe应用笔记
  18. OC 创建单例
  19. grep用法详解:grep与正则表达式
  20. mysql安装 2018最新安装mysql教程及遇到的问题解决Windows下

热门文章

  1. php serialize讲解与json性能测试
  2. RabbitMQ 的行为艺术
  3. setCharacterEncoding 是在request.getParameter获取参数之前 设置request的编码格式 一步到位
  4. JavaScript实现键盘操作页面跳转
  5. HDU——1394 Minimum Inversion Number
  6. ARC078 D.Fennec VS. Snuke(树上博弈)
  7. 51nod 1779逆序对统计(状压DP)
  8. POJ3294 Life Forms 【后缀数组】
  9. Codeforces Round #348 (VK Cup 2016 Round 2, Div. 2 Edition) D
  10. Educational Codeforces Round 55:B. Vova and Trophies