import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class 数的范围 {
public static void binarySearch(int arr[], int x){
int l = 0, r = arr.length-1;
while (l < r){
int mid = l + r >> 1;
// 找左边界,如果mid>=x,那么在左边,r=mid
if (arr[mid] >= x){
r = mid;
}else {
l = mid + 1;
}
}
// 如果无解就输出 -1 -1
if (arr[l] != x){
System.out.println(-1 + " " + -1);
}else {
int l1 = 0, r1 = arr.length-1;
while (l1 < r1){
int mid1 = l1 + r1 + 1 >> 1;
// 找右边界,如果mid<=x,那么在右边,l=mid
if (arr[mid1] <= x){
l1 = mid1;
}else {
r1 = mid1 - 1;
}
}
// 现在找到了左右边界,直接输出
System.out.println(l+" "+l1);
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int arrLength,queryNumbers;
String[] strings = br.readLine().split(" ");
// 数组长度和查询次数
arrLength = Integer.parseInt(strings[0]);
queryNumbers = Integer.parseInt(strings[1]);
// 数组内容
int[] arr = new int[arrLength];
String[] arrStrs = br.readLine().split(" ");
for (int i = 0; i < arrLength; i++) {
arr[i] = Integer.parseInt(arrStrs[i]);
}
// 进行查询
while (queryNumbers-- >0){
int x = Integer.parseInt(br.readLine());
binarySearch(arr,x);
}
}
}
标签:arr,java,int,mid,io,import,范围
From: https://www.cnblogs.com/YaoMa/p/18009978