LC 599. Minimum Index Sum of Two Lists
Posted kykai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LC 599. 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: ["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).
参考答案
1 class Solution 2 public: 3 vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) 4 5 vector<string> res; 6 unordered_map<string, int> map; 7 for(size_t i = 0 ; i< list1.size(); i++) 8 map[list1[i]] = i ; // list1 = key ; i = value ; 9 10 size_t min = INT_MAX; 11 12 for(size_t i = 0 ; i<list2.size();i ++) 13 auto iter = map.find(list2[i]); 14 if(iter != map.end()) 15 if(iter->second + i< min ) 16 min = map[list2[i]] + i; 17 res.assign(1,list2[i]); // 直接把值赋给第一个,不需要clear然后重新赋值 18 19 else if(iter->second + i == min) 20 res.push_back(list2[i]); 21 22 23 24 25 return res; 26 27 ;
分析备注
1. for 循环中,int 替换为 size_t 可以加速。
2. vector.assign(1,value) 可以实现 清除+赋值 两步操作。
3. 使用 iter -> first 和 iter -> second 可以更快。
以上是关于LC 599. Minimum Index Sum of Two Lists的主要内容,如果未能解决你的问题,请参考以下文章
599. Minimum Index Sum of Two Lists
599. Minimum Index Sum of Two Lists
599. Minimum Index Sum of Two Lists
Leetcode_easy599. Minimum Index Sum of Two Lists