LeetCode 三数之和算法题

  1. 题目
    给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
    示例:
    给定数组 nums = [-1, 0, 1, 2, -1, -4],
    满足要求的三元组集合为:
    [
    [-1, 0, 1],
    [-1, -1, 2]
    ]
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/3sum
  2. 思路
    1.先将数组排序,目的是便于去重,以及在特殊情况下,让程序提前结束
    2.使用三个指针,第一个指针从数组第一个元素遍历到最后一个元素;第二个指针从第一个指针后一位往后遍历,第三个指针从数组最后一位元素往前遍历
    3.当数组元素相同时,要跳过
  3. 代码
public List<List<Integer>> threeSum(int[] nums) {
    
    
        List<List<Integer>> dest = new ArrayList<>();
        int len = nums.length;
        Arrays.sort(nums); // 排序(默认从小到大)
        if (len < 3||nums[len-1]<0) {
    
    
            return dest;
        }
        for (int i = 0; i < len; i++) {
    
    
            if (nums[i] > 0) {
    
    
                break; // 如果当前数字大于0,则三数之和一定大于0,所以结束循环
            }
            if (i > 0 && nums[i] == nums[i - 1]) {
    
    
                continue;
            }
            int L = i + 1;
            int R = len - 1;

            while (L < R) {
    
    
                int sum = nums[i] + nums[L] + nums[R];
                if (sum == 0) {
    
    
                    dest.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 {
    
    
                    R--;
                }
            }
        }
        return dest;
    }

猜你喜欢

转载自blog.csdn.net/weixin_51681634/article/details/112252547