题目:
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: ["Shogun", "Tapioca Express", "Burger King", "KFC"] ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"] Output: ["Shogun"] Explanation: The only restaurant they both like is "Shogun".
Example 2:
Input: ["Shogun", "Tapioca Express", "Burger King", "KFC"] ["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).
Note:
- The length of both lists will be in the range of [1, 1000].
- The length of strings in both lists will be in the range of [1, 30].
- The index is starting from 0 to the list length minus 1.
- No duplicates in both lists.
思路:
基本思路是:1)对于list2中的每个string,在list1中进行查找,如果找到了,就计算它们的index之和,并记录下来。最后返回index之和最小的所有string即可。
用暴力搜索法的话时间复杂度是O(mn),其中m和n分别是list1和list2的长度。但是我们可以首先建立一个hash1,为list1中的string到其index的映射(这样就可以在O(1)的时间复杂度内找到list1中的某个string),然后建立一个从int到vector<string>的映射hash2,一旦在list1中找到了list2中的某个单词,就将其加入该映射。最后返回hash2中key最小的值即可。这样时间复杂度就降低到O(n)了,而且只需要两遍扫描。
代码:
class Solution {
public:
vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
unordered_map<string, int> hash1;
for (int i = 0; i < list1.size(); ++i) {
hash1[list1[i]] = i;
}
unordered_map<int, vector<string>> hash2;
int min_index_sum = INT_MAX;
for (int i = 0; i < list2.size(); ++i) {
auto it = hash1.find(list2[i]);
if (it != hash1.end()) {
hash2[i + it->second].push_back(list2[i]);
min_index_sum = min(min_index_sum, i + it->second);
}
}
return hash2[min_index_sum];
}
};