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 可以更快。

  • 相关阅读:
    前端css常用class命名id命名
    javaScript获取url问号后面的参数
    ASP.NET MVC 基础知识整理(一)
    Java基础概念(二)
    Java基础概念(一)
    ionic隐藏头部导航栏
    ionic开发中页面跳转隐藏底部Ttab
    /Date(1354116249000)/ 这样的格式怎么转成时间格式 JS
    ionic ng-repeat 循环传值
    ionic页面跳转传值 ng-click
  • 原文地址:https://www.cnblogs.com/kykai/p/11614338.html
Copyright © 2011-2022 走看看