[Leetcode] 259. 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?

思路

由于本题目是求三个数的和,并且不要求返回索引位置(只要求返回符合条件的triple个数),所以可以首先花费O(nlogn)的时间复杂度进行排序。为了将时间复杂度降低到O(n^2),我们采用一个技巧,就是利用start的递增性和end的递减性。例如对于start = i + 1,假设我们找到了一个合适的end,使得i和[start, end]之间的数构成的triple都满足条件,那么对于start = i + 2, ... nums.size() - 2,其对应的end必然是逐渐递减的。因此,我们不需要对每个start都用二分法查找合适的end,只需要在第二重循环中,要么增加start,要么减少end(如果用普通的思路做,则算法的时间复杂度是O(n^2logn))。

代码

class Solution {
public:
    int threeSumSmaller(vector<int>& nums, int target) {
        if(nums.size() < 3) {
            return 0;
        }
        sort(nums.begin(), nums.end());
        int ret = 0, sum = 0;
        for(int i = 0; i < nums.size() - 2; ++i) {
            int start = i + 1, end = nums.size() - 1;
            while(start < end) {
                sum = nums[i] + nums[start] + nums[end];
                if(sum < target) {
                    ret += (end - start++);     // all the ones satisfy the requirement
                }
                else {
                    --end;
                }
            }
        }
        return ret;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值