AcWing 789. 数的范围
原题链接
简单
背模板
C++ 代码
#include<iostream>
using namespace std;
const int N = 1e6 + 10;
int q[N];
int main()
{
int n, m;
cin >> n >> m;
for(int i = 0; i < n; i++) cin >> q[i];
while(m--)
{
int x;
cin >> x;
int l = 0, r = n - 1;
while(l < r)
{
int mid = l + r >> 1;
if(q[mid] >= x) r = mid;
else l = mid + 1;
}
if(q[l] != x) cout << "-1 -1" << endl;
else
{
cout << l << " ";
int l = 0, r = n - 1;
while(l < r)
{
int mid = l + r + 1>>1;
if(q[mid] <= x) l = mid;
else r = mid - 1;
}
cout << l << endl;
}
}
}
Java 代码
import java.util.Scanner;
public class Main
{
static final int N = 1000010;
static final int q[] = new int[N];
public static void main(String[] args)
{
Scanner get = new Scanner(System.in);
int n = get.nextInt();
int m = get.nextInt();
for(int i = 0; i < n; i++)
q[i] = get.nextInt();
while(m > 0)
{
int x = get.nextInt();
int l = 0, r = n - 1;
while(l < r)
{
int mid = l + r >> 1;
if(q[mid] >= x) r = mid;
else l = mid + 1;
}
if(q[l] != x) System.out.println("-1 -1");
else
{
System.out.print(l + " ");
l = 0;
r = n - 1;
while(l < r)
{
int mid = l + r + 1 >> 1;
if(q[mid] <= x) l = mid;
else r = mid - 1;
}
System.out.println(l);
}
m--;
}
}
}