题目描述:
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.
class Solution {
public:
vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
unordered_map<string,int> index;
for(int i=0;i<list1.size();i++) index[list1[i]]=i;
int min_sum=INT_MAX;
vector<string> result;
for(int i=0;i<list2.size();i++)
{
if(index.count(list2[i]))
{
if(index[list2[i]]+i<min_sum)
{
min_sum=index[list2[i]]+i;
result.clear();
result.push_back(list2[i]);
}
else if(index[list2[i]]+i==min_sum) result.push_back(list2[i]);
}
}
return result;
}
};
本文介绍了一个算法,用于解决两个人如何从各自的餐厅列表中找到共同喜欢且列表下标和最小的餐厅。通过使用哈希表记录一个列表中每个餐厅的下标,然后遍历另一个列表检查是否有共同餐厅,并更新最小下标和结果。

164

被折叠的 条评论
为什么被折叠?



