栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LeetCode刷题实战599:两个列表的最小索引总和

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode刷题实战599:两个列表的最小索引总和

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 两个列表的最小索引总和,我们先来看题面:

https://leetcode-cn.com/problems/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.

假设 Andy 和 Doris 想在晚餐时选择一家餐厅,并且他们都有一个表示最喜爱餐厅的列表,每个餐厅的名字用字符串表示。

你需要帮助他们用最少的索引和找出他们共同喜爱的餐厅。如果答案不止一个,则输出所有答案并且不考虑顺序。你可以假设答案总是存在。

示例

示例 1:

输入: list1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"],list2 = ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
输出: ["Shogun"]
解释: 他们唯一共同喜爱的餐厅是“Shogun”。

示例 2:

输入:list1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"],list2 = ["KFC", "Shogun", "Burger King"]
输出: ["Shogun"]
解释: 他们共同喜爱且具有最小索引和的餐厅是“Shogun”,它有最小的索引和1(0+1)。

解题

直接用map记录返回

第一眼看这个题目的时候,我的第一反应这不就是找出最喜欢的餐厅列表么,那不就是求公共集么。我就首先想到了,使用map记录下输入1,然后再输入2中查找,如果能查找到第一个,就直接返回第一个。

class Solution {
  public String[] findRestaurant(String[] list1, String[] list2) {

    if (list1 == null || list2 == null) {
      return new String[0];
    }

    Set dataSet = new HashSet<>(list2.length);
    for (int i = 0; i < list2.length; i++) {
      dataSet.add(list2[i]);
    }

    // 查找共同的爱好
    for (int i = 0; i < list1.length; i++) {
      if (dataSet.contains(list1[i])) {
        return new String[] {list1[i]};
      }
    }

    return new String[0];
  }
}

上期推文:

LeetCode1-580题汇总,希望对你有点帮助!

LeetCode刷题实战581:最短无序连续子数组

LeetCode刷题实战582:杀掉进程

LeetCode刷题实战583:两个字符串的删除操作

LeetCode刷题实战584:寻找用户推荐人

LeetCode刷题实战585:2016年的投资

LeetCode刷题实战586:订单最多的客户

LeetCode刷题实战587:安装栅栏

LeetCode刷题实战588:设计内存文件系统

LeetCode刷题实战589:N 叉树的前序遍历

LeetCode刷题实战590:N 叉树的后序遍历

LeetCode刷题实战591:标签验证器

LeetCode刷题实战592:分数加减运算

LeetCode刷题实战593:有效的正方形

LeetCode刷题实战594:最长和谐子序列

LeetCode刷题实战595:大的国家

LeetCode刷题实战596:超过5名学生的课

LeetCode刷题实战597:好友申请 I:总体通过率

LeetCode刷题实战598:范围求和 II

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/860968.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号