Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.
Example 1:
Input: list1 = [“Shogun”,“Tapioca Express”,“Burger King”,“KFC”], list2 = [“Piatti”,“The Grill at Torrey Pines”,“Hungry Hunter Steakhouse”,“Shogun”]
Output: [“Shogun”]
Explanation: The only restaurant they both like is “Shogun”.
Example 2:
Input: list1 = [“Shogun”,“Tapioca Express”,“Burger King”,“KFC”], list2 = [“KFC”,“Shogun”,“Burger King”]
Output: [“Shogun”]
Explanation: The restaurant they both like and have the least index sum is “Shogun” with index sum 1 (0+1).
Example 3:
Input: list1 = [“Shogun”,“Tapioca Express”,“Burger King”,“KFC”], list2 = [“KFC”,“Burger King”,“Tapioca Express”,“Shogun”]
Output: [“KFC”,“Burger King”,“Tapioca Express”,“Shogun”]
Example 4:
Input: list1 = [“Shogun”,“Tapioca Express”,“Burger King”,“KFC”], list2 = [“KNN”,“KFC”,“Burger King”,“Tapioca Express”,“Shogun”]
Output: [“KFC”,“Burger King”,“Tapioca Express”,“Shogun”]
Example 5:
Input: list1 = [“KFC”], list2 = [“KFC”]
Output: [“KFC”]
Constraints:
1 <= list1.length, list2.length <= 1000
1 <= list1[i].length, list2[i].length <= 30
list1[i] and list2[i] consist of spaces ’ ’ and English letters.
All the stings of list1 are unique.
All the stings of list2 are unique.
以任意一个list作为键,其下标作为key,然后进行判断即可。
#include <bits/stdc++.h>
class Solution {
public:
map<string,int> mp;
bool findstr(string str,vector<string> list1,vector<string> list2){
bool f1 = false;
bool f2 = false;
for(int i=0; i<list1.size(); i++){
if(list1[i] == str){
f1 = true;
break;
}
}
for(int i=0; i<list2.size(); i++){
if(list2[i] == str){
f2 = true;
break;
}
}
if(f1 && f2){
return true;
}
return false;
}
vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
int len1 = list1.size();
string str;
int k = 50000;
for(int i=0; i<len1; i++){
str = list1[i];
mp[str] = i;
}
int len2 = list2.size();
for(int i=0; i<len2; i++){
if(mp.count(list2[i])){
// cout<<list2[i]<<endl;
mp[list2[i]] += i;
if(mp[list2[i]] < k){
k = mp[list2[i]]; /*找出最小的k值,因为可能有多个出现次数最小的字符串*/
}
}
}
vector<string> ss;
for(auto i = mp.begin(); i!=mp.end(); i++){
// cout<<i->first<<" "<<i->second<<endl;
if(i->second == k && findstr(i->first,list1,list2)){
ss.push_back(i->first);
}
}
return ss;
}
};