vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
vector<string> res;
string str="";
int l1=list1.size(),l2=list2.size(),sum=l1+l2;
for(int i=0;i<l1;i++){
for(int j=0;j<l2;j++){
if(list1[i]==list2[j]){
if(i+j<sum){
sum=i+j;
res.clear();
res.push_back(list1[i]);
}else if(i+j==sum){
res.push_back(list1[i]);
}
}
}
}
return res;
}
优化后的代码
vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
int n=list1.size(),m=list2.size(),sum=INT_MAX;
vector<string> res;
unordered_map<string,int>m1;
for(int i=0;i<n;i++)
m1[list1[i]]=i;
for(int i=0;i<m;i++){
if(m1.count(list2[i]))
if(i+m1[list2[i]]<sum){
sum=i+m1[list2[i]];
res.clear();
res.push_back(list2[i]);
}else if(i+m1[list2[i]]==sum){
res.push_back(list2[i]);
}
}
return res;
}