guimei121212 @ 2024-10-02 00:26:48
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int const N = 100000;
int const M = 100000;
int main() {
int n, m;
cin >> n >> m;
int a[N], c[N], b[M];
for (int i = 1; i <= n; i++) {
scanf("%d", &c[i]);
}
for (int i = 1; i <= m; i++) {
scanf("%d", &b[i]);
}
int num = 0;
for (int i = 1; i <= n; i++) {
if (i == 1 || c[i] != c[i - 1]) {
a[i - num] = c[i];
} else {
num++;
}
}
n -= num;
for (int i = 1; i <= m; i++) {
int l = 1, r = n, mid;
bool found = false;
while (l <= r) {
mid = l + (r - l) / 2;
if (a[mid] == b[i]) {
printf("%d", mid);
found = true;
break;
} else if (a[mid] > b[i]) {
r = mid - 1;
} else {
l = mid + 1;
}
}
if (!found) {
printf("-1");
}
if (i < m) {
printf(" ");
}
}
printf("\n");
return 0;
}
by laotingrui @ 2024-10-07 14:53:50
@guimei121212 \ 看看我的 求关~~
#include<iostream>
using namespace std;
int n,m,f[1000005],d;
//二分查找
int check(int x){
int l=1,r=n,mid;
while(l<=r){
mid=(l+r)/2;//找中间数
if(f[mid]>=x) r=mid-1;
//就算找到了,也不一定是第一个
else l=mid+1;
}
if(f[l]==x) return l;
else return -1;
}
int main(){
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++) scanf("%d",&f[i]);
for(int i=1;i<=m;i++){
scanf("%d",&d);
printf("%d ",check(d));
}
return 0;
}