3Sum_Leetcode_#15
来源:互联网 发布:java面向对象易错题 编辑:程序博客网 时间:2024/06/07 06:05
1.题目
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]
]
2.解法
思路:先给nums排序,最大值nums[nums.length - 1]与最小值nums[0]之间的距离为gap,取一个数组countNum用来统计nums[i] - nums[0]出现的次数。以-nums[0]作为基准base,(-nums[0] > 0),取x < base, y > base, x < z < y.找到符合x+y+z=3*base的条件的x,y,z.则x-base,y-base,z-base就是一个解。
时间复杂度为O(N^2)
public class Solution { public List<List<Integer>> threeSum(int[] nums){ List arr = new ArrayList(); int size = nums.length; if(size == 0){ return arr; } Arrays.sort(nums); int gap = nums[size - 1] - nums[0] + 1; int[] countNum = new int[gap]; for(int i = 0; i < size; i++){ countNum[nums[i] - nums[0]]++; } int base = -nums[0]; if(base < 0 || base >= countNum.length){ return arr; } if(countNum[base] >= 3){ arr.add(new int[]{0, 0, 0}); } //x-base <0, y-base>0, x<z<y for(int x = 0; x < base; x = findNextLtBase(countNum, x)){ for(int y = countNum.length - 1; y > base; y = findNextGtBase(countNum, y)){ int z = 3 * base - x - y; if(z == x && countNum[x] >= 2 || z == y && countNum[y] >= 2 || z > x && z < y && countNum[z] >= 1){ arr.add(new int[]{x - base, y - base, z - base}); } } } return arr; } public int findNextLtBase(int[] countNum, int m){ for(++m; m < countNum.length; ++m){ if(countNum[m] > 0){ return m; } } return m; } public int findNextGtBase(int[] countNum, int m){ for(--m; m >= 0; --m){ if(countNum[m] > 0){ return m; } } return m; }}
0 0
- 3Sum_Leetcode_#15
- Two Sum_leetcode_#1
- 4Sum_Leetcode_#18
- Combination Sum_Leetcode_#39
- 3-15
- 3月15日
- 3月15号
- 3月15日
- 3-15 记录
- 15周任务3
- 15周任务3
- Leetcode 15 3Sum
- 例题3-15
- LeetCode 15: 3Sum
- 15-3成绩单折腾
- 15周问题3
- leetcode 15 3Sum
- [leetcode 15] 3Sum
- 由先序中序求后序
- HDU 3555 Bomb
- 正在进行简易安装时 无法手动启动 vmware tools 安装 的解决方法
- 8.2 Dictionary类
- storm单机安装
- 3Sum_Leetcode_#15
- 串口数据的格式问题
- 长瘦管道的MSS对TCP性能的影响
- hdfs 文件权限设计
- Python利用朴素贝叶斯进行评分的分类
- Find them, Catch them--POJ 1703带权并查集
- Hdu 5456 Matches Puzzle Game (记忆化搜索) 2015 ACM-ICPC沈阳网赛
- linux各文件夹的作用
- Android NDK 开发