Leetcode 259: 较小的三数之和 3Sum Smaller

题目描述:

Given an array of n integers nums and an integer 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.

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

Example 1:

Input: nums = [-2,0,1,3], target = 2
Output: 2
Explanation: Because there are two triplets which sums are less than 2:
[-2,0,1]
[-2,0,3]

Example 2:

Input: nums = [], target = 0
Output: 0

Example 3:

Input: nums = [0], target = 0
Output: 0

Constraints:

n == nums.length
0 <= n <= 300
-100 <= nums[i] <= 100
-100 <= target <= 100

Time complexity: O O O( N 2 N^{2} N2)
Space complexity: O O O( 1 1 1)
双指针:
根据解决此类较简单的问题twoSum版本,现排序,然后我们可以用通向双指针找到满足两数之和小于target的index即 nums[i]+nums[j]<target。左指针从左往右递增,右指针从右往左递减。注意在此题中,要求我们找到所有满足的组合后数。所以以 [1, 2, 3, 5, 8], target=7. 为例子,当左指针 left 指向1,右指针 right 指向5满足 1 + 5 < 7 后我们发现因为数组是排过序的则[1, 2], [1, 3]也都满足条件,所以 总的组合数 sum += right - left;

class Solution {
    public int threeSumSmaller(int[] nums, int target) {
         Arrays.sort(nums);
        int sum = 0;
        for(int i = 0; i < nums.length-2; i++){
            sum += twoSumSmaller(nums, i+1, target - nums[i]);
        }
        return sum;
    }
    
    private int twoSumSmaller(int[] nums, int start, int target){
        int sum = 0;
        int left = start;
        int right = nums.length - 1;
        while(left < right){
            if(nums[left] + nums[right] < target){
                sum += right - left;
                left++;
            }else{
                right--;
            }
        }
        return sum;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值