Problem Description:
Suppose Andy and Doris want to choose a restaurant for dinner, and they have expressed a favorite restaurant list, the name of each restaurant is represented by a string.
You need to help them with a minimum of index and find out their common favorite restaurant . If the answer is more than one output all the answers and do not consider the order. You can assume that there is always an answer.
Example 1:
Enter: [ "Shogun", "Tapioca Express", "Burger King", "KFC"] [ "Piatti", "at The Grill AT Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"] Output: [ "Shogun" ] explanation: their only common favorite restaurant is "Shogun".
Example 2:
Enter: [ "Shogun", "Tapioca Express", "Burger King", "KFC"] [ "KFC", "Shogun", "Burger King"] Output: [ "Shogun"] to explain: they co-favorite with minimal index and restaurant are "Shogun", which has the smallest index and 1 (0 + 1).
prompt:
- Length two lists are [1, 1000] within.
- Length of the string within the two lists will be in the range [1,30] of.
- Index from 0 to 1 minus the length of the list.
- Both lists are no duplicate elements.
The basic idea:
First establish repetitive elements and their indexing and mapping .
And then find the smallest index.
In order to return the index and the minimum index and the same for all the elements, then sweep again obtained .
AC Code:
class Solution {
public:
vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
// 找到重复的字符串,记录他们重复的元素以及对应的索引和
map<string, int> m;
for (int i = 0; i < list1.size(); ++i) {
auto it = find(list2.begin(), list2.end(), list1[i]);
if (it != list2.end()) {
m[list1[i]] = (it - list2.begin()) + i;
}
}
// 遍历hashmap,找到最小的索引和
int min_index = INT_MAX;
string min_string;
for (auto i = m.begin(); i != m.end(); ++i) { // hashmap的iterator使用pair的方式来访问key和value
if (i->second < min_index) {
min_index = i->second;
min_string = i->first;
}
}
// 返回结果集
vector<string> res;
for (auto i = m.begin(); i != m.end(); ++i) {
if (i->second == min_index) {
res.push_back(i->first);
}
}
return res;
}
};