3Sum Smaller

本文详细解析了LeetCode上3SumSmaller问题的解决方案,采用先排序再使用双指针的方法来寻找数组中三个数之和小于目标值的组合数量。通过枚举第一个数并利用双指针技巧高效解决问题。

3Sum Smaller

题目链接:https://leetcode.com/problems...

  1. sort,从小到大排序

  2. 固定第一个数字index = i,从后面的数字里选第二个第三个

  3. 后两个数字,用2 points来找,从j = i + 1, k = len() - 1开始:

    • if n[j] + n[k] < target - n[i]: count += (k-i), j++
      因为所有(j+1, k)之间的数和n[j]组合都< target - n[i]

    • if n[j] + n[k] >= target - n[i]: k--

public class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        if(nums == null || nums.length < 3) return 0;
        // sort first
        Arrays.sort(nums);
        /* enumerate 1st num: k
         * 2 points find 2nd, 3rd
         * initial: i = k + 1, j = len(nums) - 1
         * case 1: n[i] + n[j] < target - n[k]: count += j - i, i++
         * case 2: > : j--
         */
        int count = 0;
        for(int k = 0; k < nums.length - 2; k++) {
            int i = k + 1, j = nums.length - 1;
            while(i < j) {
                if(nums[i] + nums[j] >= target - nums[k]) j--;
                else {
                    count += j - i;  i++;
                }
            }
        }
        return count;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值