LeetCode 259. 3Sum Smaller(三数值和)

36 篇文章 0 订阅
20 篇文章 0 订阅

原题网址: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?

方法一:暴力解法。

public class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        int counts = 0;
        for(int i=0; i<nums.length-2; i++) {
            for(int j=i+1; j<nums.length-1; j++) {
                for(int k=j+1; k<nums.length; k++) {
                    if (nums[i]+nums[j]+nums[k]<target) counts ++;
                }
            }
        }
        return counts;
    }
}

方法二:使用TreeMap。

public class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        if (nums == null || nums.length < 3) return 0;
        int counts = 0;
        TreeMap<Integer, Integer> treemap = new TreeMap<>();
        treemap.put(nums[0], 1);
        for(int i=1; i<nums.length-1; i++) {
            for(int j=i+1; j<nums.length; j++) {
                for(int count: treemap.headMap(target-nums[i]-nums[j]).values()) {
                    counts += count;
                }
            }
            Integer count = treemap.get(nums[i]);
            if (count == null) count = 1; else count ++;
            treemap.put(nums[i], count);
        }
        return counts;
    }
}

方法三:由于题目只要求统计结果,不需要范围原始的下标组合,因此完全可以对数组进行排序!一开始就是因为不敢排序,所以想不到这个方法。

思路:多个数值和问题都可以用类似的解法,这道题的特点在于条件隐含,第二个数从左边开始,第三个数从右边开始,当三数值和小于target,隐含的条件是第二个数和第三个之间的任何一对数字都能够符合条件。

public class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        Arrays.sort(nums);
        int count = 0;
        for(int i=0; i<nums.length-2; i++) {
            int j=i+1, k=nums.length-1;
            while (j<k) {
                if (nums[i]+nums[j]+nums[k] < target) {
                    count += k-j;
                    j ++;
                } else {
                    k --;
                }
            }
        }
        return count;
    }
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值