15. 3Sum
来源:互联网 发布:极限音波拉皮 知乎 编辑:程序博客网 时间:2024/06/08 04:55
转载自 http://algorithm.books.mafengshe.com/answer/3.html
15. 3Sum
题目描述:
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]]
题目翻译
一个包含n个整数的数组S,判断S中是否存在元素a + b + c = 0,查找数组中所有和为零的三元组。
注意:解决方案集不能包含重复的三元组。
例如,数组S = [-1,0,1,2,-1,-4]答案是:[ [-1 , 0 , 1], [-1 , -1 , 2]]
解题方案
标签: Array
思路:
- 首先对数组进行排序,时间复杂度为O(n*logn)
- 然后对数组进行两层的遍历,先取出当前遍历的数字为nums[i],然后从数组两侧取出数字分别为nums[begin]和nums[end],然后三个数求和值为sum
- sum == 0,将三个数加入结果之中,同时将两侧的下标向中间移动,直到不与之前取出的数字相同,避免出现重复的三元组
- sum > 0,因为数组有序,说明右侧的数字过大,所以下标左移,故而执行end–
- sum < 0,因为数组有序,说明左侧的数字过小,所以下标右移,所以执行begin++
- 因为两层的遍历时间复杂度为O(n^2),O(n*logn) + O(n^2) = O(n^2),所以总体时间复杂度为O(n^2)
代码:
public class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); int len=nums.length; if(len<3)return res; Arrays.sort(nums); for(int i=0;i<len;i++){ if(nums[i]>0)break; if(i>0 && nums[i]==nums[i-1])continue; int begin=i+1,end=len-1; while(begin<end){ int sum=nums[i]+nums[begin]+nums[end]; if(sum==0){ List<Integer> list = new ArrayList<Integer>(); list.add(nums[i]);list.add(nums[begin]);list.add(nums[end]); res.add(list); begin++;end--; while(begin<end && nums[begin]==nums[begin-1])begin++; while(begin<end && nums[end]==nums[end+1])end--; }else if(sum>0)end--; else begin++; } } return res; } }
参考资料
http://blog.csdn.net/runningtortoises/article/details/45604601
- 15. 3Sum && 16 sum closet && 18 4sum
- 15. 3Sum 和 18. 4Sum
- 1. Two Sum&15. 3Sum
- LeetCode 15. 3Sum
- LeetCode --- 15. 3Sum
- [Leetcode] 15. 3Sum
- 【LeetCode】15. 3Sum
- 15. 3Sum
- 【leetcode】15. 3sum
- 【leetcode】15. 3Sum
- 15. 3Sum
- [leetcode] 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- leetcode 15. 3Sum
- 大数据研发岗面经小结(涉及阿里,网易 云音乐以及商汤科技)
- springboot整合mybatis
- 一文清晰讲解机器学习中梯度下降算法(包括其变式算法)
- 重磅 | 最全PPT实录!英伟达发布可编程AI推理加速器TensorRT
- 学Java还是Python?一张图告诉你!
- 15. 3Sum
- 一文讲述如何将预测范式引入到机器学习模型中
- 资源 | 8张思维导图帮你梳理深度学习&机器学习多个知识点
- 探索 | 神经网络到底是如何思考的?MIT精英们做了这么一个实验室来搞清楚
- 如何优雅地用TensorFlow预测时间序列:TFTS库详细教程
- 课程 | 想成为高薪、抢手又能改变世界的机器学习工程师?
- 经验 | 如何高效学Python?
- utuntu unicode打印中文
- 挑战程序设计竞赛 算法和数据结构 第12章 图