15. 三数之和

### 解题思路

按照leetcode官方题解的写法,采用双指针进行优化

  1. 三重循环枚举每一个数字。
  2. 第一个优化,为了不产生重复的res结果,首先对 n u m s nums nums数组进行一个排序, i = 0 , j = i + 1 , k = j + 1 i=0,j=i+1,k=j+1 i=0,j=i+1,k=j+1这个样子的一直往后枚举,枚举的时候需要去重,具体的说就是说每一个数字比如2在 i i i这一层循环里只枚举一次。
  3. f i r s t first first+ s e c o n d second second+ t h i r d third third=0对于这个,我们得到 t h i r d = − ( f i r s t + s e c o n d ) third=-(first+second) third=(first+second),当 s e c o n d second second朝增大的方向走的时候, t h i r d third third是朝着变小的方向走的,于是 s e c o n d second second t h i r d third third这边可以使用双指针进行优化。
  4. 具体的优化方法看上面的leetcode的官方题解。
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        int n=nums.size();
        vector<vector<int>>ans;
        if(n<3){
            return ans;
        }
        // vector<int>tmp(3);
        sort(nums.begin(),nums.end());
        for(int first=0;first<n;first++){
            // 去重
            if(first>0&&nums[first]==nums[first-1]){
                continue;
            }
            
            int target=-(nums[first]);
            int third=n-1;
            for(int second=first+1;second<n;second++){
                // 去重
                if(second>first+1&&nums[second]==nums[second-1]){
                    continue;
                }
                
                while(second<third&&nums[second]+nums[third]>target){
                    third--;
                }
                if(second==third){
                    break;
                }
                if(nums[second]+nums[third]==target){
                    ans.push_back({nums[first],nums[second],nums[third]});
                }
            }
        }
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值