AcWing 789. 数的范围 -- java
原题链接
简单
作者:
ice_73
,
2025-01-17 22:55:48
,
所有人可见
,
阅读 1
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
/**
* @author iceewei
* @Description: 二分查找 acwing-ycx
* @date 2025/1/17
*/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer st = new StreamTokenizer(br);
st.nextToken();
int n = (int)st.nval;
st.nextToken();
int m = (int)st.nval;
int[] q = new int[n];
for (int i = 0; i < n; i++) {
st.nextToken();
q[i] = (int)st.nval;
}
while (m-- > 0) {
st.nextToken();
int x = (int)st.nval;
System.out.println(leftBound(q, x) + " " + rightBound(q, x));
}
}
private static int rightBound(int[] q, int x) {
int l = 0, r = q.length - 1;
while (l < r) {
int mid = (l + r + 1) >> 1;
if (q[mid] <= x) l = mid;
else r = mid - 1;
}
return q[l] != x ? -1 : l;
}
private static int leftBound(int[] q, int x) {
int l = 0, r = q.length - 1;
while (l < r) {
int mid = (l + r) >> 1;
if (q[mid] >= x) r = mid;
else l = mid + 1;
}
return q[l] != x ? -1 : l;
}
}