码迷,mamicode.com
首页 > 其他好文 > 详细

LC 599. Minimum Index Sum of Two Lists

时间:2019-09-30 23:35:43      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:需要   choice   ini   dex   nes   val   example   assign   参考答案   

题目描述

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

标签:需要   choice   ini   dex   nes   val   example   assign   参考答案   

原文地址:https://www.cnblogs.com/kykai/p/11614338.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!