题目
599.两个列表的最小索引总和
题目大意
假设 Andy 和 Doris 想在晚餐时选择一家餐厅,并且他们都有一个表示最喜爱餐厅的列表,每个餐厅的名字用字符串表示。
你需要帮助他们用最少的索引和找出他们共同喜爱的餐厅。 如果答案不止一个,则输出所有答案并且不考虑顺序。 你可以假设答案总是存在。
样例
数据规模
思路
使用哈希表unordered_map
,首先遍历list1
中的每一个字符串,在哈希表中进行标记。
定义一个最小索引和minn
以及答案数组vector ans
。
遍历list2
中的每一个字符串,并且判断mp[list2[i]]
是否存在,并且计算索引和,如果可以更新minn
则需要清空答案数组ans
,然后加入当前的字符串;如果恰好等于最小索引和,那么直接将该字符串加入数组即可。
代码
// short int long float double bool char string void
// array vector stack queue auto const operator
// class public private static friend extern
// sizeof new delete return cout cin memset malloc
// relloc size length memset malloc relloc size length
// for while if else switch case continue break system
// endl reverse sort swap substr begin end iterator
// namespace include define NULL nullptr exit equals
// index col row arr err left right ans res vec que sta
// state flag ch str max min default charray std
// maxn minn INT_MAX INT_MIN push_back insert
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e6+50;//注意修改大小
long long read(){long long x=0,f=1;char c=getchar();while(!isdigit(c)){if(c=='-') f=-1;c=getchar();}while(isdigit(c)){x=x*10+c-'0';c=getchar();}return x*f;}
ll qpow(ll x,ll q,ll Mod){ll ans=1;while(q){if(q&1)ans=ans*x%Mod;q>>=1;x=(x*x)%Mod;}return ans%Mod;}
class Solution {
public:
vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
unordered_map<string,int>mp;
for(int i=0;i<list1.size();i++){
mp[list1[i]]=i+1;
}
vector<string>ans;
int minn=0x3f3f3f3f;
for(int i=0;i<list2.size();i++){
if(mp[list2[i]]&&minn>i+mp[list2[i]]-1){
ans.clear();
ans.push_back(list2[i]);
minn=i+mp[list2[i]]-1;
}
else if(mp[list2[i]]&&minn==i+mp[list2[i]]-1){
ans.push_back(list2[i]);
}
}
return ans;
}
};