美文网首页
算法----三数相加

算法----三数相加

作者: 咕哒咕 | 来源:发表于2021-02-25 10:08 被阅读0次

    给定一个包含n个整数的数组,判断其中是否存在三个元素相加和为0,如果有输出和为0且不重复的三元组。

    eg.

    输入:nums = [-1,0,1,2,-1,-4]
    输出:[[-1,-1,2],[-1,0,1]]
    

    解法:排序+双指针

    ① 先将数组排序

    ② 对数组进行遍历,nums[i],使用左右指针指向数组剩余的两端,计算三个数的和是否为0。

    ※ nums[i]>0;和一定大于零,结束循环;

    ※ nums[i] == nums[i+1] 需要去重

    ※ 左指针L nums[L] == nums[L+1] 需要去重 L ++;

    ※ 右指针R nums[R] == nums[R-1] 需要去重 R --;

    class Solution {
        public static List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> result = new ArrayList();
            int length = nums.length;
            if(nums == null || len < 3) return result;
            Arrays.sort(nums); // 排序
            for (int i = 0; i < length ; i++) {
                if(nums[i] > 0) break; // 如果当前数字大于0,则三数之和一定大于0,结束循环
                if(i > 0 && nums[i] == nums[i-1]) continue; // 去重
                int L = i+1;
                int R = length-1;
                while(L < R){
                    int sum = nums[i] + nums[L] + nums[R];
                    if(sum == 0){
                        result.add(Arrays.asList(nums[i],nums[L],nums[R]));
                        while (L<R && nums[L] == nums[L+1]) L++; // 去重
                        while (L<R && nums[R] == nums[R-1]) R--; // 去重
                        L++;
                        R--;
                    }
                    else if (sum < 0) L++;
                    else if (sum > 0) R--;
                }
            }        
            return result;
        }
    }
    

    相关文章

      网友评论

          本文标题:算法----三数相加

          本文链接:https://www.haomeiwen.com/subject/pvlsfltx.html