xingyu671 @ 2023-07-25 14:50:22
#include<iostream>
#include<cmath>
#include<string>
using namespace std;
int a[1000005];
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 x,h = n,l = 0,mid;
cin >> x;
if(x > a[n] || x < a[1])
{
cout << "-1 ";
continue;
}
while(l <= h)
{
mid = (l+h)/2;
if(a[mid] == x)
{
cout << mid << ' ';
break;
}
else if(a[mid] > x)
{
h = mid-1;
}
else
{
l = mid+1;
}
}
if(l > h) cout << "-1 ";
}
return 0;
}
by eggy_LIKE @ 2024-08-16 11:31:01
#include<bits/stdc++.h>
using namespace std;
int a[1000005], x, n, m;
void solve() {
cin >> x; // 输入当前查询的数字
int l = 1, r = n, ans = -1; // 初始化二分查找的左右边界和结果
// 二分查找
while(l<=r) {
int mid = l+(r-l)/2; // 计算中间位置
if(a[mid] == x) {
ans = mid; // 找到目标值
r = mid-1; // 缩小右边界
} else if(a[mid] > x) {
r = mid-1; // 缩小右边界
} else {
l = mid+1; // 缩小左边界
}
}
cout << ans << " "; // 输出结果
}
int main() {
cin >> n >> m; // 输入 n 和 m
for(int i = 1; i <= n; i++) {
cin >> a[i]; // 输入序列中的 n 个数
}
while(m--) solve();
return 0;
}