- Minimum Index Sum of Two Lists
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).
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.
solution
思路与算法
使用一个哈希表记录 \textit{list}_1list
1
中每个餐厅对应的索引下标,然后遍历 \textit{list}_2list
2
,如果 \textit{list}_2list
2
中的餐厅存在于哈希表中,那么说明该餐厅是两人共同喜爱的,计算它的索引和。如果该索引和比最小索引和小,则清空结果,将该餐厅加入结果中,该索引和作为最小索引和;如果该索引和等于最小索引和,则直接将该餐厅加入结果中。
代码
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;
}
vector<string> ret;
int indexSum = INT_MAX;
for (int i = 0; i < list2.size(); i++) {
if (index.count(list2[i]) > 0) {
int j = index[list2[i]];
if (i + j < indexSum) {
ret.clear();
ret.push_back(list2[i]);
indexSum = i + j;
} else if (i + j == indexSum) {
ret.push_back(list2[i]);
}
}
}
return ret;
}
};
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/minimum-index-sum-of-two-lists/solution/liang-ge-lie-biao-de-zui-xiao-suo-yin-zo-5m9w/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。