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]
]

题解

class Solution {
    
    
    public List<List<Integer>> threeSum(int[] nums) {
    
    
       List<List<Integer>> result = new ArrayList<>();
        if (nums == null || nums.length < 3) {
    
    
            return result;
        }
        Arrays.sort(nums);
        int low,high,sum;
        for (int i = 0; i < nums.length - 2 && nums[i] <= 0; i ++) {
    
    
            if (i > 0 && nums[i] == nums[i - 1]) {
    
    
                continue;
            }
            low = i + 1;
            high = nums.length - 1;
            while (low < high) {
    
    
                sum = nums[i] + nums[low] + nums[high];
                if (sum == 0) {
    
    
                    result.add(Arrays.asList(nums[i], nums[low], nums[high]));
                    while (low < high && nums[low] == nums[low + 1]) {
    
    
                        low++;
                    }

                    while (low < high && nums[high] == nums[high - 1]) {
    
    
                        high--;
                    }
                    low ++;
                    high--;
                } else if (sum < 0) {
    
    
                    low++;
                } else {
    
    
                    high--;
                }
            }
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_49249294/article/details/108894979