算法练习专题——LeetCode系列之 ThreeSum
来源:互联网 发布:淘宝卖家工具源码 编辑:程序博客网 时间:2024/05/31 19:50
Question:
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.
假设现有一个拥有n个整数的数组S,要求找出所有不重复的数组中任意三个和为0的整数组合。
Example:
For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ] 注意,[-1, 0, 1] 和[0, 1, -1]属于重复组合,结果中只能出现一个!
Answer Template:
class Solution { public List<List<Integer>> threeSum(int[] nums) { }}
Solution:
这个题目的解题关键在于,先将整个数组排序,这样相等的整数就会相邻,然后我们从左往右遍历num.length-2个元素,对于每一个元素,我们对剩下的元素进行一次双向的遍历,并过滤掉重复的元素。
public static List<List<Integer>> threeSum(int[] nums) { //先将整个数组排序 Arrays.sort(nums); List<List<Integer>> result = new ArrayList<>(); for(int i=0; i<nums.length-2; i++) { //如果nums[i]与前一个元素相同,则跳过 if(i==0 || (i>0&&nums[i]!=nums[i-1])) { //li为左向遍历的索引,ri为右向遍历的索引,sum为num[i]的相反数 int li=i+1, ri=nums.length-1, sum = 0-nums[i]; //只要两个索引没有相交 while(li<ri) { //两数相加等于sum if(nums[li]+nums[ri] == sum) { //在result中增加这三个数的组合 result.add(Arrays.asList(nums[i],nums[li],nums[ri])); //继续遍历,跳过重复元素 while(li<ri && nums[li]==nums[li+1]) li++; while(li<ri && nums[ri]==nums[ri-1]) ri--; li++; ri--; } //如果两数相加小于sum,左索引+1,去找更大的数 else if(nums[li] +nums[ri] <sum) { //继续遍历,跳过重复元素 while(li<ri && nums[li]==nums[li+1]) li++; li++; } //如果两数相加大于sum,又索引-1,去找更小的数 else { //继续遍历,跳过重复元素 while(li<ri && nums[ri]==nums[ri-1]) ri--; ri--; } } } } return result; }
本节博客的源码全部放在这里,欢迎大家下载,下载后记得修改源码中的package名字哦。
阅读全文
1 0
- 算法练习专题——LeetCode系列之 ThreeSum
- 算法练习专题——LeetCode系列之 Two Sum
- LeetCode之ThreeSum
- LeetCode ThreeSum
- leetcode : threesum
- Leetcode 之 twoSum, ThreeSum, FourSum(K-Sum)问题
- LeetCode(M)threesum
- [LeetCode]15.threeSum
- leetcode 15 threeSum
- 算法练习系列—hiho1039 字符消除
- 算法练习系列—hiho1039 字符消除
- 算法练习系列—hiho1122二分图最大匹配之匈牙利算法
- threeSum
- threeSum
- threeSum
- leetcode 专题—sort
- ETL系列专题3——ETL之E
- ETL系列专题5——L之DimLoad
- 原生JDBC连接总结
- ruby环境sass编译中文出现Syntax error: Invalid GBK character错误解决方法
- abap中,ftp上传文件demo
- 深入理解Linux内核3
- 改变this指向的三种常用方法
- 算法练习专题——LeetCode系列之 ThreeSum
- 系统监控工具Atop
- Linux的下编译PHP常见错误及解决方法
- OrgJson解析Json数据
- 获取文件和图片的方法
- C# 4.0 之线程安全集合篇
- 此图片来自微信公众平台 未经允许不可引用
- word的api
- Memcache技术精华