leetcode.15 三数之和

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

思路:利用滑动窗口思想,先将数组排好序,然后选定一个数作为 target,这样就将问题转换为求两个数的和等于这个 target 的问题,然后从 target 的位置出发,用 i 和 j 指针规划一个 [ i , j ] 的 窗口,其中 i 是大于 target 的位置的,而 j 是小于数组长度的位置的, 如果 nums[i] + nums[j] 的值和 target 相等,那么加入 res,如果小于 target,则 i++,如果大于 target,则 j--。其中还要考虑到去重的问题。

代码:

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList();
        Arrays.sort(nums);
        for(int k=0;k<nums.length;k++){
            int i = k+1,j = nums.length - 1;//***
            while(i < j){              
                int value = nums[i] + nums[j];
                if(value == (-nums[k])){
                    List<Integer> list = new ArrayList();
                    list.add(nums[k]);
                    list.add(nums[i]);
                    list.add(nums[j]);
                    res.add(list);
                    //重值处理
                    //****一定要有i < j条件,否则i会到最后
                    while(i<j && nums[i] == nums[i+1]){
                        i++;
                    }
                    //****一定要有i < j条件,否则j会取-1
                    while(i<j && nums[j] == nums[j-1]){
                        j--;
                    }
                    //***
                    i++;
                    j--;
                }
                else if(value < (-nums[k]))
                    i++;
                else
                    j--;
            }
            //****重值处理
            while(k < nums.length-1 && nums[k] == nums[k+1]){
                k++;
            }
        }
        return res;
    }
}


作者:Mr_Curious_ 
来源:CSDN 
原文:https://blog.csdn.net/xuchonghao/article/details/79837681 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/weixin_40904220/article/details/84870783