LeetCode 15. 3Sum -- 数组中某三个元素之和为0,输出这三个元素的值,且这个三元组唯一
来源:互联网 发布:淘宝店铺手机怎么激活 编辑:程序博客网 时间:2024/06/05 19:41
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]]
public class Solution {public List<List<Integer>> threeSum(int[] num) { Arrays.sort(num); List<List<Integer>> res = new LinkedList<>();//保证输出的顺序就是插入的顺序 for (int i = 0; i < num.length - 2; i++) {//比如:{-4, -1, -1, 0, 1, 5 ,5},最后一次比较的是1,5,5 if (i == 0 || (i - 1 >= 0 && num[i] != num[i - 1])) {//比如-1只能做基准1次,后面的-1直接跳过 int low = i + 1; int high = num.length - 1;//最后一次num[i] = 1,num[low] = 5,num[high] = 5 while (low < high) { if (num[i] + num[low] + num[high] == 0) { res.add(Arrays.asList(num[i], num[low], num[high])); while (low < high && num[low] == num[low + 1]) low++;//比如:{-4, -1, -1, 0, 1, 5 ,5},-1只能计算一次,不然会有重复 while (low < high && num[high] == num[high - 1]) high--;//比如:{-4, -1, -1, 0, 1, 5, 5},5只能计算一次,不然会有重复 low++; high--; } else if (num[i] + num[low] + num[high] < 0) { low++; } else high--; } } } return res; }//threeSum}313 / 313 test cases passed.
Status: Accepted
Runtime: 77 ms
Your runtime beats 87.59 % of java submissions.
T(n) = O(n^2)
阅读全文
0 0
- LeetCode 15. 3Sum -- 数组中某三个元素之和为0,输出这三个元素的值,且这个三元组唯一
- LeetCode18--4Sum--数组中某四个元素之和为某个输入的数值,输出这四个元素的值,并且这个四元组唯一
- [LeetCode] 3Sum 找出所有三个元素之和为0的组合
- 在一个数组中找到三元组,使得三元组内的三个元素加和为0。
- LeetCode 16. 3Sum Closest--寻找数组中的三个元素和,该和与给定的值的差最小,输出这个和(三个元素可以不连续)
- 3Sum(数组中三个数之和为零)
- leetcode-java.T015_3Sum---给定一个n个元素的数组,是否存在a,b,c三个元素,使用得a+b+c=0,找出所有符合这个条件的三元组
- 3Sum:带重复数组中取三个元素求和为零
- [LeetCode]—3Sum Closest 求数组中三个数之和最接近给定target的组合
- 求无序数组中三个元素相加与目标数最接近的三元素之和
- LeetCode 15. 3Sum 三个正数之和
- 3sum 三个数之和为0
- 3Sum 找出数组中的三元组,满足三元组之和为0
- 三个数组的共同元素
- C语言 输出一个数组中,所有元素之和为0的子序列
- LeetCode 454. 4Sum II--在四个等长的数组中,找到有多少个四元组的数值之和为0(每个数组中各占一个元素)
- 求已知集合中某两个或三个元素之和等于确定值问题
- 求已知集合中某两个或三个元素之和等于确定值问题 收藏
- JavaScript流程控制
- Channel Allocation (涂颜色)(dfs)
- 购物车(2)优化代码
- 7.3 TensorFlow笔记(基础篇):加载数据之从队列中读取
- 第二个程序之图像腐蚀
- LeetCode 15. 3Sum -- 数组中某三个元素之和为0,输出这三个元素的值,且这个三元组唯一
- HDU 6078 Wavel Sequence 计数dp(思维)
- HDU-2017 多校训练赛4-1012-Wavel Sequence
- 三级菜单(1)
- 使用python3 连接SQL SERVER 2016
- 2017.08.05小结
- 字符串转整数函数stoi()实现
- 哈密尔顿环
- Git 原理 流程 命令