zoukankan      html  css  js  c++  java
  • 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 可以更快。

  • 相关阅读:
    centos7安装rabbitmq 总结
    python第六十三天-- 第十一周作业
    python第六十一天,第六十二天 redis
    python第六十天-----RabbitMQ
    python第五十四天--第十周作业
    python第五十三天--进程,协程.select.异步I/O...
    python第五十二天---第九周作业 类 Fabric 主机管理程序
    python第五十一天----线程,Event,队列
    Python基础之-面向对象编程(引言)
    Python中的模块
  • 原文地址:https://www.cnblogs.com/kykai/p/11614338.html
Copyright © 2011-2022 走看看