【数据结构基础_数组】Leetcode 15.三数之和

原题链接:Leetcode 15. 3 Sum

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation: 
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.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.

Example 2:

Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.

Example 3:

Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.

Constraints:

  • 3 <= nums.length <= 3000
  • -105 <= nums[i] <= 105

方法一:双指针

思路:

采用固定一个点,然后用双指针遍历去找另外两个点的方法
问题在于 如何去重

步骤:

  1. 特判,对于数组长度小于 3,返回。
  2. 对数组进行排序
  3. 遍历排序后数组:
    • 若 nums[i]>0,后面不可能有三个数加和等于0,直接返回结果
    • 对于重复元素:跳过,避免出现重复解
    • 令左指针 L=i+1,右指针 R=n−1,当 L<R 时,执行循环:
      满足条件时,加入结果,判断左界和右界是否和下一位置重复,去除重复解。并将两个指针移动
      若和大于 0,说明 nums[R] 太大,R 左移
      若和小于 0,说明 nums[L] 太小,L 右移

c++代码:

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums){
        vector<vector<int>> ans;

        // 特判
        if(nums.size() < 3 || nums.empty()) 
            return ans; 

        int n = nums.size();
        sort(nums.begin(), nums.end());

        // nums[i]是三个数中的最小数
        for(int i = 0; i < n; i++ ){
            if(nums[i] > 0) 
                return ans;

            // 对最小数去重
            if(i > 0 && nums[i] == nums[i-1])
                continue;

            // 两个指针 nums[l]为中间值 nums[r]为最大值
            int l = i + 1;
            int r = n - 1;

            while(l < r){
                int x = nums[l] + nums[r] + nums[i];

                if(x == 0){
                    ans.push_back({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(x > 0) 
                    r--;
                    
                // 小了就让中间值变大
                else        
                    l++;
            }
        }
        return ans;
    }
};

复杂度分析:

  • 时间复杂度:O(n2),大头在循环。遍历左节点n,在它基础上再遍历双指针是O(n2)。排序的O(nlogn)忽略
  • 空间复杂度:O(1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值