对左右边界查找的函数封装
把函数封装 方便使用 :)
import java.util.*;
import java.io.*;
public class Main{
private static final int N = 1000010;
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException{
String[] strs = br.readLine().split(" ");
int n = Integer.parseInt(strs[0]);
int q = Integer.parseInt(strs[1]);
strs = br.readLine().split(" ");
int[] arr = new int[N];
for(int i = 0; i < n ;++i){
arr[i] = Integer.parseInt(strs[i]);
}
int tar,left;
while(q-- != 0){
strs = br.readLine().split(" ");
tar = Integer.parseInt(strs[0]);
left = getLeftBoundary(arr,tar,n);
System.out.println(left+" "+(left == -1 ? -1 : getRightBoundary(arr,tar,n)));
}
}
// 查找一个数字在数组中的左边界索引
public static int getLeftBoundary(int[] arr,int target,int n){
int mid,l = 0,r = n - 1;
while(l < r){
mid = (l + r) >> 1;
if(arr[mid] < target) l = mid + 1;
else r = mid;
}
return arr[l] != target ? -1 : l;
}
// 查找一个数字在数组中的右边界索引
public static int getRightBoundary(int[] arr,int target,int n){
int mid,l = 0, r = n - 1;
while(l < r){
mid = l + r + 1 >> 1;
if(arr[mid] > target) r = mid - 1;
else l = mid;
}
return arr[l] != target ? -1 : l;
}
}