[leetcode 259]3Sum Smaller

Question:

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(n^2) runtime?


分析:

题意要求给定一个有n个整数的数组和一个目标数据target,求解在数组中找到满足 0 <= i < j < k < n,且nums[i] + nums[j] + nums[k] < target. 的 三个下标i,j,k组的组数。

可以知道,数组元素的顺序并不影响下标i,j,k对应的三元素数组;比如【1,4,2,3】如果target为7,则i=0,j=2,k=3---【1,3,2】。更改数组顺序【1,2,3,4】下标为i=0,j=1,k=2但是对应的三元素数组仍为【1,2,3】.

所以在解决问题时候可以先将原数组从小到大排序。

此时,i从0开始。而j最初从i+1开始,k从n-1开始,如果nums[i] + nums[j] + nums[k] < target. ,这说明下标k在j~k之间的数组元素都满足要求,然后继续++j开始。否则k--。


代码如下:

<span style="font-size:14px;">class Solution {
public:
    int threeSumSmaller(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int n = nums.size(), ans = 0, i, j, k;
        for (int i = 0; i < n - 2; i++) {
            int j = i + 1, k = n - 1;
            while (j < k) {
                if (nums[i] + nums[j] + nums[k] >= target) k--;
                else {
                    ans += (k - j);
                    j++;
                }
            }
        }
        return ans;
    }
};</span>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值