
一、核心思路
(1)采用哈希表实现
(2)二分查找实现
二、代码实现
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e5 + 10;
int n, q, t;
unordered_map<int, int> mp;
signed main()
{
cin >> n;
for(int i = 1; i <= n; i++)
{
int x; cin >> x;
mp[x] = i;
}
cin >> q;
while(q–)
{
cin >> t;
cout << mp[t] << endl;
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e5 + 10;
struct node{
int index;
int value;
};
bool cmp(node& a,node& b)
{
return a.value < b.value;
}
int n, q, t;
node a[N];
int check(int t)
{
int l = 1, r = n;
while(l < r)
{
int mid = (l + r + 1) >> 1;
if(a[mid].value > t) r = mid -1;
else l = mid;
}
if (a[l].value == t) return a[l].index;
else return 0;
}
signed main()
{
cin >> n;
for(int i = 1; i <= n; i++)
{
cin >> a[i].value;
a[i].index = i;
}
sort(a+1, a+n+1, cmp);
cin >> q;
while(q–)
{
cin >> t;
cout << check(t) << endl;
}
return 0;
}
网硕互联帮助中心



评论前必须登录!
注册