试题
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);
}
}