N个建筑,选择3个作为埋伏点,要求距离小于D

本文探讨了一道算法题目,给定N个已排序的建筑位置,选择3个作为埋伏点,要求这3个点的距离小于D。通过双指针技巧,高效地计算出所有符合条件的组合数量。

试题
N个建筑,选择3个作为埋伏点,要求3个埋伏点距离小于D。输入已排序好,求方案数量。
代码
以end表示当前建筑必须包含在方案里。使用前后两个指针维持所有与end距离小于D的建筑。

import java.util.*;

public class Main{
    public static void main(String[] args){
//        int[] A = {1,10,20,30,50};
//        int d = 19;
        int[] A = {1,2,3,4};
        int d = 3;

        if(A==null || A.length<3) System.out.println(0);
        int len = A.length;

        int total=0;
        int start=0,end=2;
        int count = 3;

        while(end<len){
            while(start<end && A[end]-A[start]>d){
                start ++;
                count--;
            }
            if(count>2){
                total += (count-2)*(count-1)/2;
            }
            end++;
            count++;
        }
        System.out.println(total);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值