1:回溯法:超时
/**
* className:test2
* Package:PACKAGE_NAME
*
* @Author:swx
* @Create2024/1/1020:57
* @version:1.0
*/
import java.util.*;
public class test2 {
static LinkedList<Integer> path = new LinkedList<>();
static int result = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num1 = scanner.nextInt(); // 建筑物的位置
int num2 = scanner.nextInt(); // 两名特工相聚的最大距离
int[] building = new int[num1];
for (int i=0; i<num1; i++) {
building[i] = scanner.nextInt();
}
Arrays.stream(building).sorted();
backtracking(building, num2, 0);
System.out.println(result);
}
private static void backtracking(int[] building, int num2, int startIndex) {
if (path.size() == 3) {
result+=1;
return;
}
for (int i=startIndex; i<building.length; i++) {
path.add(building[i]);
if (path.peekLast() - path.peekFirst() <= num2) {
backtracking(building, num2, i + 1);
path.removeLast();
}
else
path.removeLast();
}
}
}
2:快慢指针法:
import java.util.Scanner;
/**
* @author guizimo
* @date 2020/7/17 10:04 下午
*/
public class test_2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int n = scanner.nextInt();
int d = scanner.nextInt();
int[] position = new int[n];
scanner.nextLine();
for (int i = 0; i < n; i++) {
position[i] = scanner.nextInt();
}
run(n, d, position);
}
}
public static void run(int n, int d, int[] position) {
long sum = 0L;
long mod = 99997867;
// 采用快慢指针 其中i为快至指针 j为慢指针
for (int i = 0, j = 0; i < n; i++) {
//从第三个开始判断,判断是否违法,如果违法j++
while (i >= 2 && position[i] - position[j] > d) {
j++;
}
//计算合法的次数,n(n-i)/2
/*
* 比如对于 1, 2, 3, 4这四个建筑 最大距离和最小距离不大于3
* 当i=2,j=0。 此时只有一个情况就是(1,2,3).此时一个特工已经在第三个建筑了即i=2,另外两个特工从前2个任选2个不重复的就是C22
* 当i=3,j=0时依然满足情况。此时一个特工已经在第三个建筑了即i=3,另外两个特工从前3个任选2个不重复的就是C32
* 依次类推
* */
sum += (long) (i - j) * (long) (i - j - 1) / 2;
}
System.out.println(sum % mod);
}
}