Two Sum - Less than or equal to target Lintcode

本文介绍了一种寻找数组中所有数对的方法,这些数对的和小于或等于特定的目标值。通过将数组排序并使用双指针技巧,有效地解决了这个问题。文章详细解释了解决方案,并提供了一个简洁的Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array of integers, find how many pairs in the array such that their sum is less than or equal to a specific target number. Please return the number of pairs.

Example

Given nums = [2, 7, 11, 15], target = 24
Return 5
2 + 7 < 24
2 + 11 < 24
2 + 15 < 24
7 + 11 < 24
7 + 15 < 25

这道题自己乱写了半天。。。但是屡清思路的话就很简单。。。= =
把数组排序。先把首尾相加,如果小于等于target,就说明每个数和第一个数相加都是小于target的,这个时候count += end - start。此时需注意把start往前挪一位继续进行计算。如果大于target,就说明最后一个数太大了,往前挪一个。
另外注意一下终止条件,一开始写的是start + 1 < end,但是这样子start + 1 == end的时候不会判断,所以条件是start < end。
回顾一下吧,思路还比较巧妙。
public class Solution {
    /**
     * @param nums an array of integer
     * @param target an integer
     * @return an integer
     */
    public int twoSum5(int[] nums, int target) {
        if (nums == null || nums.length < 2) {
            return 0;
        }
        Arrays.sort(nums);
        int start = 0;
        int end = nums.length - 1;
        int count = 0;
        while (start < end) {
            if (nums[start] + nums[end] <= target) {
                count += end - start;
                start++;
            } else {
                end--;
            }
        }
        return count;
    }
}

 

转载于:https://www.cnblogs.com/aprilyang/p/6697330.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值