[leetcode] 259. 3Sum Smaller 解题报告

本文介绍了一个LeetCode上的经典问题“3Sum Smaller”的解决方案。通过对数组进行排序,并采用固定一个数,使用双指针法来查找其余两个数的方法,实现了在O(N^2)的时间复杂度内解决问题的目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接: https://leetcode.com/problems/3sum-smaller/

Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.

For example, given nums = [-2, 0, 1, 3], and target = 2.

Return 2. Because there are two triplets which sums are less than 2:

[-2, 0, 1]
[-2, 0, 3]

Follow up:
Could you solve it in O(n2) runtime?


思路:首先对数组进行排序. 然后同样是先确定一位, 然后双指针一个在最左边, 一个在最右边. 如果三个数的和小于target, 也就是nums[i]+nums[left]+nums[right] < target, 那么在区间[left+1, right-1]之间的所有数+nums[i]+nums[left]一定<target, 因为这个区间的数都小于nums[right], 所以一次可以得到几个组合方式, 也就是right-left个答案. 然后再让left++, 继续做即可. 注意到这个之后就可以很容易得到答案. 时间复杂度O(N^2).

代码如下:

class Solution {
public:
    int threeSumSmaller(vector<int>& nums, int target) {
        int cnt = 0, len = nums.size();
        sort(nums.begin(), nums.end());
        for(int i = 0; i< len-2; i++)
        {
            int left = i+1, right = len -1;
            while(left < right)
            {
                int val = nums[i]+nums[left]+nums[right];
                if(val < target) cnt+= (right-left++);
                else right--;
            }
        }
        return cnt;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值