AcWing 789. 数的范围 Java
原题链接
简单
作者:
leo_0
,
2021-07-19 04:22:46
,
所有人可见
,
阅读 219
Java 代码
import java.util.*;
public class Main{
static int[] tmp;
static long res = 0;
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
int q = sc.nextInt();
int[] nums = new int[n];
for(int i = 0; i < n; i++){
nums[i] = sc.nextInt();
}
for(int i = 0; i < q; i++){
int k = sc.nextInt();
int[] res = search(nums, k);
System.out.println(res[0]+" "+res[1]);
}
}
private static int[] search(int[] nums, int k){
int l = 0;
int r = nums.length-1;
int[] res = new int[2];
res[0] = -1;
res[1] = -1;
// find left pos
while(l < r){
int mid = l + (r-l)/2;
if(nums[mid] < k){
l = mid+1;
}else{
r = mid;
}
}
if(nums[l] == k){
res[0] = l;
}
// find right pos
l = 0;
r = nums.length-1;
while(l < r){
int mid = l+1 + (r-l)/2;
if(nums[mid] > k){
r = mid-1;
}else{
l = mid;
}
}
if(nums[r] == k){
res[1] = r;
}
return res;
}
}