P1102 A-B 数对 二分
java
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//A-B=C
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int C = sc.nextInt();
int[] res = new int[n+1];
for(int i=1;i<=n;i++) {
res[i] = sc.nextInt();
}
Arrays.sort(res,1,n+1);//1
long ans = 0;//2
for(int i=1;i<=n;i++) {//枚举B
int l1 = i,r1 = n;//二分A
while(l1<r1) {
int mid = (l1+r1)/2;
if(res[mid]-res[i]>=C) r1 = mid;
else l1 = mid+1;
}
int l2 = i,r2 = n;
while(l2<r2) {
int mid = (l2+r2+1)/2;
if(res[mid]-res[i]<=C) l2 = mid;
else r2 = mid-1;
}
if(res[l2] - res[i] == C) {
ans+=(l2-l1)+1;
}
}
System.out.println(ans);
}
}
789. 数的范围 二分
java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] res = new int[n];
for(int i=0;i<n;i++)
res[i] = sc.nextInt();
while(k--!=0) {
int x = sc.nextInt();
//先大于等于再小于等于
int l1 = 0,r1 = n-1;
while(l1<r1) {
int mid1 = (l1+r1)/2;
if(res[mid1]>=x) r1 = mid1;
else l1 = mid1+1;
}
if(res[l1] == x) {
int l2 = 0,r2 = n-1;
while(l2<r2) {
int mid2 = (l2+r2+1)/2;
if(res[mid2]<=x) l2 = mid2;
else r2 = mid2-1;
}
System.out.println(l1+" "+l2);
}else {
System.out.println("-1 -1");
}
}
}
}