第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

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res=new ArrayList<>();
        if(nums==null || nums.length<3){
            return res;
        }

        Arrays.sort(nums);
        for(int i=0;i<nums.length;i++){
            //因为是排序好的,如果第一个数就是大于0了,后面都大于0,所以不会有相加等于0的可能
            if(nums[i]>0){
                return res;
            }
            //排除重复
            if(i>0&&nums[i-1]==nums[i]){
                continue;
            }
            int target=-nums[i];
            int L=i+1;
            int R=nums.length-1;
            while(L<R){
              // int temp=nums[L]+nums[R];
               if(nums[L]+nums[R]<target){
                   L++;
               }else if(nums[L]+nums[R]>target){
                   R--;
               }else{
                   //收集集🈴️:Arrays.asList(1,2,3);
                   res.add(Arrays.asList(nums[i],nums[L],nums[R]));
                    L++;
                    R--;
                    while(L<R&&nums[L-1]==nums[L]){
                        L++;
                    }
                    while(L<R && nums[R+1]==nums[R]){
                        R--;
                    }
                 }   
               }
            }

       return res;
     
    }
}

  

posted @ 2021-09-25 23:10  sherry001  阅读(36)  评论(0编辑  收藏  举报