leetcode——15.三数之和

提示

两数之和只差了一个数字,可以将第一个数作为target,便转为两数之和

思路——双向指针

  1. 如何使双向指针有效运作?——对数组进行排序

  2. 如何将三数之和转为两数之和?——以第一个元素为target进行寻找

  3. target如何去重选择?避免second错过与first相同的值,每次取重复中的第一个数字

  4. 如何避免得到重复的答案?——second third同时移动 跳过相同的元素

代码

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> ans;
        sort(nums.begin(), nums.end());//使用双向指针需要对数组进行排序
        int n = nums.size();
        //遍历数组 寻找出多个不同的first作为target
        for (int first = 0; first < n - 1; first++) {
        	//这里要是重复就取重复中的第一个数字
            if (first > 0 && nums[first] == nums[first - 1])
                continue;
            else {
            	//将第一个元素看成target
                int target = -nums[first];
                //将 三数之和 转换为 两数之和 问题
                int second = first + 1, third = n - 1;
                while (second < third) {
                    if (nums[second] + nums[third] == target)
                    {
                        ans.push_back({ nums[first],nums[second],nums[third] });
                        //如果找到了 second third就同时移动 并跳过相同元素
                        int second_val = nums[second];
                        int third_val = nums[third];
                        do { second++; } 
                        while (second < third && nums[second] == second_val);
                        do { third--; }
                        while (second < third && nums[third] == third_val);
                    }
                    else if (nums[second] + nums[third] < target)
                        second++;
                    else
                        third--;
                }
            }
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值