_Satoru_ @ 2024-05-29 23:02:39
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int q = scan.nextInt();
int[] arr = new int[n];
int[] k = new int[q];
for(int i = 0;i<n;i++) {
arr[i]=scan.nextInt();
}
for(int i=0;i<q;i++) {
k[i]=scan.nextInt();
}
for(int i=0;i<q;i++) {
int l = -1;
int r = n;
int mid = 0;
while(l+1!=r) {
mid=(l+r)/2;
if(arr[mid]<k[i]) {
l=mid;
}else {
r=mid;
}
}
if(r>=n||arr[r]!=k[i]) {
System.out.print(-1+" ");
continue;
}
System.out.print(r+1+" ");
}
}
}
by chrispang @ 2024-05-29 23:07:47
我也才刚写完这道题
#include <iostream>
using namespace std;
int n, m, a[1000010];
int erfen(int x) {
int l = 1, r = n;
while (l < r) { //最后l和r会相等
int mid = l + (r - l) / 2;
if (a[mid] >= x) r = mid;
else l = mid + 1;
}
if (a[l] == x) return l;
else return -1;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++)
cin >> a[i];
for (int i = 1; i <= m; i++) {
int q; cin >> q;
cout << erfen(q) << " ";
}
return 0;
}