leetcode -- 15. 3Sum 【问题转化2sum + 避免重复计算的方法(规定次序)】
2017-10-02 17:57
531 查看
题目
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] ]
题意
在给定的数组S中寻找3个数的和为0的情况。分析及解答
【转化】 将 3sum 转化为2sum的问题进行处理,即 固定一个 数,然后去按照2sum的方式进行处理。【避免重复计算】为了避免一些不必要的元素重复加入到结果集中,我们需要适当的限定遍历的次序。(代码中标号3的注释部分)
代码
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
//1.排序。
Arrays.sort(nums);
//2.选取c(不同于上次所选),然后 寻找a,b 满足 a + b = -c。
//3.a,b,c记录放入的集合S.(如何做到不重复放入呢?规定次序:只能在c的右边空间中寻找)
List<List<Integer>> results = new ArrayList<>();
int c = 0;
for(int i = 0 ; i < nums.length ; i++){
if(i == 0){
c = nums[i];
}else if(nums[i] == c){
continue;
}else{
c = nums[i];
}
for(int p1 = i+1,p2= nums.length -1 ;p1 < p2;){
if(nums[p1] + nums[p2] + c == 0){
//加入结果集中。
List<Integer> result = new ArrayList<>(3);
result.add(c);
result.add(nums[p1]);
result.add(nums[p2]);
results.add(result);
while(p1 < p2 && nums[p1] == nums[++p1]){ // 这里出现了一些bug,注意。
}
while(p1 < p2 && nums[p2] == nums[--p2]){
}
}else if(nums[p1] + nums[p2] + c < 0){
p1++;
}else if(nums[p1] + nums[p2] + c > 0){
p2--;
}
}
}
return results;
}
}
相关文章推荐
- leetcode 15. 3Sum 以及2Sum的问题的处理和求解
- 动态规划:0-1背包问题(使用迭代方法,避免重复计算)
- [Leetcode][求和问题2Sum/3Sum/4Sum/KSum]相关题目汇总/分析/总结
- Subsets II [leetcode] 从获取子集的递归和循环方法说起,解决重复子集的问题
- 避免超时方法一 :不要重复调用函数计算同一个数
- leetCode 15. 3Sum (3数之和) 解题思路和方法
- 避免程序重复运行的简单处理方法
- Delphi中避免程序重复运行的方法
- JavaScript中避免Form重复提交几个方法
- C#中避免相同MDI子窗口重复打开的方法
- excel 复制公式计算结果问题的解决方法
- FORM表单重复提交问题解决方法
- SQL 重复记录问题的处理方法小结
- 多线程中生成随机数序列重复问题的解决方法
- delphi子窗体重复打开问题解决方法
- 数据结构中Catalan数用格路问题进行转化后的一种证明方法
- 关于Struts2.0中重复提交问题的解决方法
- delphi子窗体重复打开问题解决方法
- 关于无线数据传输中产生的流量的一些计算方法以及问题!