AcWing 789. 数的范围
原题链接
简单
作者:
Broken_
,
2024-09-26 18:36:12
,
所有人可见
,
阅读 2
java 代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static final int N = 100010;
static int[] a = new int[N];
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] s1 = in.readLine().split(" ");
int n = Integer.parseInt(s1[0]);//数组长度为n
int q = Integer.parseInt(s1[1]);//q次查询
String[] s2 = in.readLine().split(" ");
for(int i = 0; i < n; i ++) a[i] = Integer.parseInt(s2[i]);
while(q -- > 0) {
int k = Integer.parseInt(in.readLine());
//二分查找
int l = 0, r = n - 1;
while(l < r) {
int mid = l + r >> 1;
if(a[mid] >= k) r = mid;
else l = mid + 1;
}
if(a[l] != k) System.out.println("-1 -1");
else {
int left = l;
l = 0;
r = n - 1;
while(l < r) {
int mid = l + r + 1 >> 1;
if(a[mid] <= k) l = mid;
else r = mid -1;
}
System.out.println(left + " " + l);
}
}
}
}