leetcode— 3Sum
来源:互联网 发布:java调用通用短信接口 编辑:程序博客网 时间:2024/06/05 10: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]
]
class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new ArrayList<>(); if(nums==null || nums.length<3) return res; Arrays.sort(nums); for(int i=0; i<nums.length-2; i++){ if(i>0 && nums[i]==nums[i-1]) continue; int left = i+1; int right = nums.length-1; int target = 0-nums[i]; while(left<right){ if(nums[left]+nums[right]==target){ res.add(Arrays.asList(nums[i],nums[left],nums[right])); while(left<right && nums[left]==nums[left+1]) left++; while(left<right && nums[right]==nums[right-1]) right--; left++; right--; }else if(nums[left]+nums[right]>target){ right--; }else{ left++; } } } return res; }}
**本题目的思路是先将数组排序,对于数组中的每一个元素,对[i+1,nums.length-1]应用two sum,只不过这里不能使用hashmap,要利用夹逼准则,解释一个问题,为什么是从[i+1,nums.length-1]中的i+1开始呢?而不是直接去掉第i个元素,然后在那些元素里面应用夹逼准则呢?
我们以选第一个和第二个举例,假设数组为A[],总共有n个元素A1,A2….An。很显然,当选出A1时,我们在子数组[A2~An]中求目标位target-A1的2sum问题,我们要证明的是当选出A2时,我们只需要在子数组[A3~An]中计算目标位target-A2的2sum问题,而不是在子数组[A1,A3~An]中,证明如下:
假设在子数组[A1,A3~An]目标位target-A2的2sum问题中,存在A1 + m = target-A2(m为A3~An中的某个数),即A2 + m = target-A1,这刚好是“对于子数组[A3~An],目标位target-A1的2sum问题”的一个解。即我们相当于对满足3sum的三个数A1+A2+m = target重复计算了。因此为了避免重复计算,在子数组[A1,A3~An]中,可以把A1去掉,再来计算目标是target-A2的2sum问题**
**其次就是写程序需要注意的地方
if(i>0 && nums[i]==nums[i-1]) continue;这一个语句使用i-1而不是i+1
因为i+1会导致跳过一部分值,
while(left
- leetcode— 3Sum
- Sum—LeetCode-15 3Sum
- 【Leetcode】3Sum (Sum)
- LeetCode —— 3SUM
- LeetCode——3Sum
- 3Sum——leetcode
- 3Sum —— Leetcode
- Leetcode:2Sum,3Sum
- 【Leetcode】3Sum Closest (Sum)
- leetcode 2 sum 3sum 4sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- LeetCode——3Sum & 3Sum Closest
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- [LeetCode] K sum(2Sum、3Sum、4Sum)
- leetcode--sum集合:2sum,3sum,4sum
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- jquery中几种事件绑定的方法比较
- 机考系统公式输入扫盲帖
- 泛化误差上界的证明,说明机器能进行学习和预测的基本原理。
- oracle12c修改字段长度报错:ORA-54033要修改的列由某个虚拟表达式使用
- 判断数值中是否包含某元素并删除
- leetcode— 3Sum
- 数据结构课程设计【银行储蓄系统】
- Hadoop各商业发行版之比较
- Job for tomcat.service failed because the control process exited with error code 解决办法:
- MYSQL LIMIT函数/分页---mysql-sql
- Linux安装java8
- JS——worker
- Android6.0动态权限
- nodejs crud