3Sum LeetCode 解题报告
来源:互联网 发布:电视伴音收音机淘宝 编辑:程序博客网 时间:2024/05/18 03:30
题目
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]
]
思路
找出数组中三个数相加为0的数,不能是重复的数字组合。找三个数的和为0,可以依次取数组中一个数设为target,然后在后面找两个数,使得这两个数的和为-target,这样找出来的数相加和就为0了。
需要注意的地方:
(1)、首先对数组排序,方便后面找数字和。
(2)、使用首尾标记,分别标记target后的首尾数字nums[low]和nums[high],当nums[i+1] == nums[i]时,需要跳过,执行low++,因为这时会有重复的数字组合。同理nums[high-1] == nums[high]时,执行high–,从而避免找到重复的数字组合。
(3)、当找到的两个数和sum与-target相加不为0时,比较sum和-taget的大小,sum > -target时,说明后面两个数相加大了,high++(把和变小,这也是为什么先排序),如果sum < -target,说明后面两个数的和小了,那么low++,把后面两个数和增大。
代码和简要解析
public class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> list = new ArrayList<List<Integer>>(); Arrays.sort(nums); if(nums.length < 3) return list; for(int i = 0; i < nums.length-2; i++){ if(i == 0 || (i > 0 && nums[i] != nums[i-1])){ //这是为了避免重复的三元组,i>0避免数组越界 int low = i+1; int high = nums.length-1; int sum = -nums[i]; //取一个数的负数设为target,后面去两个数相加与target的和看是否为0 while(low < high){ if(nums[low]+nums[high] == sum){ list.add(Arrays.asList(nums[i],nums[low],nums[high])); while(low < high && nums[low] == nums[low+1]) low++; //避免重复组合 while(low < high && nums[high] == nums[high-1]) high--; //避免重复组合 low++; high--; }else if(nums[low]+nums[high] < sum){ low++; }else{ high--; } } } } return list; }}
- [LeetCode]3Sum,解题报告
- 【LeetCode】3Sum 解题报告
- LeetCode解题报告--3 Sum
- [LeetCode] 3Sum 解题报告
- 3Sum LeetCode 解题报告
- 【LeetCode】3Sum Closest 解题报告
- LeetCode 解题报告 3Sum Closest
- LeetCode解题报告--3Sum Closest
- [leetcode] 15. 3Sum 解题报告
- [leetcode] 16. 3Sum Closest 解题报告
- [leetcode] 259. 3Sum Smaller 解题报告
- leetcode(16) 3Sum Closest解题报告
- [Leetcode] 15. 3Sum 解题报告
- [Leetcode] 16. 3Sum Closest 解题报告
- [LeetCode] 3Sum Closest 解题报告
- leetcode解题报告15. 3Sum
- leetcode解题报告16. 3Sum Closest
- [Leetcode] 259. 3Sum Smaller 解题报告
- 在Android Studio下使用Hierarchy Viewer
- appium(java)——appium启动日志分析
- muduo源码学习(5)-线程封装
- Linux下定时执行查询sql语句
- pendingIntent的深入理解
- 3Sum LeetCode 解题报告
- javascript-回调
- ubuntu16.04.2修改内核启动顺序后重启机器未生效
- LabVIEW 学习_03_程序设计基础
- DFS之八皇后
- new用法
- 最详解万向锁
- HBase创建表和列出表
- SSM框架项目调用查询的方法时 报空指针异常