AcWing 789. 数的范围
原题链接
简单
作者:
将情怀讲泛滥的恶果
,
2021-05-17 19:49:13
,
所有人可见
,
阅读 250
java
import java.io.*;
public class Main{
public static void main(String[] args) throws IOException {
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
String[] res = br.readLine().split(" ");
int num = Integer.parseInt(res[0]);
int m = Integer.parseInt(res[1]);
res = br.readLine().split(" ");
int[] arrs = new int[num];
for (int i = 0; i < res.length; i++) {
arrs[i] = Integer.parseInt(res[i]);
}
while (m > 0) {
int target = Integer.parseInt(br.readLine());
int left = binary_search1(arrs, 0, arrs.length-1, target);
int right = binary_search2(arrs, 0, arrs.length-1, target);
m -= 1;
System.out.println(left + " " + right);
}
br.close();
}
public static int binary_search1(int[] nums, int left, int right, int target) {
while (left < right) {
int mid = (left + right) >> 1;
if (nums[mid] >= target) {
right = mid;
} else {
left = mid + 1;
}
}
if(nums[left]==target){
return left;
}
else{
return -1;
}
}
public static int binary_search2(int[] nums, int left, int right, int target) {
while (left < right) {
int mid = (left + right + 1) >> 1;
if (nums[mid] <= target) {
left = mid;
} else {
right = mid - 1;
}
}
if(nums[left]==target){
return left;
}
else{
return -1;
}
}
}