15. 三数之和

发布时间 2023-07-20 11:33:34作者: xiazichengxi

给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请

你返回所有和为 0 且不重复的三元组。

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


输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
解释:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0 。
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0 。
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。
不同的三元组是 [-1,0,1] 和 [-1,-1,2] 。
注意,输出的顺序和三元组的顺序并不重要。

> 思路

  1. 特判,对于数组长度 n,如果数组为 null 或者数组长度小于 3,返回 []。
  2. 对数组进行排序。
  3. 遍历排序后数组:
  • 若 nums[i]>0:因为已经排序好,所以后面不可能有三个数加和等于 0,直接返回结果。
  • 对于重复元素:跳过,避免出现重复解
  • 令左指针 L=i+1,右指针 R=n−1,当 L<R时,执行循环:
    *当 nums[i]+nums[L]+nums[R]==0 执行循环,判断左界和右界是否和下一位置重复,去除重复解。并同时将 L,R 移到下一位置,寻找新的解
    *若和大于 0,说明 nums[R]太大,R左移
    *若和小于 0,说明 nums[L]太小,L右移

> 代码


class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        int len = nums.size();
        if(len < 3) return {};
        sort(nums.begin(),nums.end());
        int i = 0;
        vector<vector<int>> ans;
        while(i < len){
            if(nums[i] > 0) break;
            int l = i+1;
            int r = len - 1;
            while(l < r){
                int x = nums[l];
                int y = nums[i];
                int z = nums[r];
                if(x + y > 0 - z){
                    r--;
                }
                else if(x + y < 0 - z){
                    l++;
                }
                else{
                    ans.push_back({nums[i], nums[l], nums[r]});
                    // 相同的left和right不应该再次出现,因此跳过
                    while(l < r && nums[l] == nums[l+1]){
                        l++;
                    }
                    while(l < r && nums[r] == nums[r-1]){
                        r--;
                    }
                    l++;
                    r--;
                }
            }
            // 避免nums[i]作为第一个数重复出现
            while(i + 1 < len && nums[i] == nums[i+1]){
                i++;
            }
            i++;
        }
        return ans;
    }
};