【Leetcode】3Sum
2016-05-31 00:47
375 查看
题目链接:https://leetcode.com/problems/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:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
思路:
先将数组排序,然后设立三个浮标,从左右向中间遍历。注意当某个triple满足条件时,为了避免重复,要移动浮标直到指向的元素发生变化。
算法:
题目:
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:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
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)
思路:
先将数组排序,然后设立三个浮标,从左右向中间遍历。注意当某个triple满足条件时,为了避免重复,要移动浮标直到指向的元素发生变化。
算法:
public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> lists = new ArrayList<List<Integer>>(); Arrays.sort(nums); for (int i1 = 0; i1 < nums.length - 2; i1++) { if (i1 == 0 || nums[i1] > nums[i1 - 1]) { // 避免重复 int i2 = i1 + 1; int i3 = nums.length - 1; while (i2 < i3) { if (nums[i2] + nums[i3] + nums[i1] == 0) { List<Integer> list = new ArrayList<Integer>(); list.add(nums[i1]); list.add(nums[i2]); list.add(nums[i3]); while (i2 < i3 && nums[i2] == nums[i2 + 1]) {// 避免跟已有结果重复 i2++; } while (i2 < i3 && nums[i3] == nums[i3 - 1]) {// 避免跟已有结果重复 i3--; } i2++; i3--; lists.add(list); } else if (nums[i2] + nums[i3] + nums[i1] > 0) { i3--; } else if (nums[i2] + nums[i3] + nums[i1] < 0) { i2++; } } } } return lists; }
相关文章推荐
- 【C语言】06-基本数据类型
- 【Leetcode】Unique Binary Search Trees II
- 【Leetcode】Maximal Square
- 【Leetcode】Range Sum Query 2D - Immutable
- Python基础入门
- 根据网卡所在的硬件接口设置IP地址
- MySQL 性能优化的最佳20多条经验分享
- linux中设置环境变量PATH的方法(转)
- spring-boot 热部署 intellij IDE(开发过程)
- QT学习笔记
- man php怎么打开
- 密码学基础之base编码家族介绍
- picasso-强大的Android图片下载缓存库
- 数据归一化
- 前端资源汇集(个人觉得不错的学习资源收集)
- unity3D-iOS工程整合爬过的坑~
- MYSQL优化原则
- 在命令行下执行php程序
- 删除电话和调制解调器选项里的我的位置里面的区号
- 选课系统设计