您的位置:首页 > 其它

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: