Bramble_Marshall @ 2024-07-16 08:01:13
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
int a[N];
int n, m;
int low_find(int num, int l, int r) {
int mid = l + (r - l) / 2;
if (l > r) return -1;
else if (a[mid] > num) return low_find(num, l, mid - 1);
else if (a[mid] < num) return low_find(num, mid + 1, r);
else while (a[mid] == num) mid--;
return ++mid;
}
// 13489 : 6
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1, tmp; i <= m; i++) {
cin >> tmp;
cout << low_find(tmp, 1, n) << ' ';
}
return 0;
}
by Youth_Glory @ 2024-07-16 08:19:00
可能是二分判断有点问题吧,你可以试着稍微改改
by eleke @ 2024-07-16 09:05:00
直接用二分函数
#include <iostream>
#include <algorithm>
using namespace std;
int a[1000010];
int main()
{
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= m; i++)
{
int t;
cin >> t;
int pos = lower_bound(a + 1, a + n + 1, t) - a;
//lower_bound(a + 1, a + n + 1, t);
//查找a数组中第一个大于等于t的数的位置
if (t == a[pos]) cout << pos << " ";
else cout << -1 << " ";
}
return 0;
}