博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode Minimum Index Sum of Two Lists
阅读量:4355 次
发布时间:2019-06-07

本文共 1678 字,大约阅读时间需要 5 分钟。

原题链接在这里:

题目:

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).

Note:

  1. The length of both lists will be in the range of [1, 1000].
  2. The length of strings in both lists will be in the range of [1, 30].
  3. The index is starting from 0 to the list length minus 1.
  4. No duplicates in both lists.

题解:

把list1的element 和对应的index放进HashMap<String, Integer> hm中. 再iterate list2, 如果list2的element在hm中比较index相加是否比minIndexSum小,若比minIndexSum小,清空res重新加, 更新minIndexSum. 若相等直接加进res中.

Time Complexity: O(list1.length + list2.length)

Space: O(list1.length).

AC Java:

1 class Solution { 2     public String[] findRestaurant(String[] list1, String[] list2) { 3         List
res = new ArrayList
(); 4 int minIndexSum = Integer.MAX_VALUE; 5 HashMap
hm = new HashMap
(); 6 for(int i = 0; i

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/7518731.html

你可能感兴趣的文章
Logstash安装和设置(图文详解)(多节点的ELK集群安装在一个节点就好)
查看>>
STM32 keil printf的使用
查看>>
C++类相关
查看>>
Sql分隔字符串方法--split
查看>>
通过meta设置防止浏览器缓存
查看>>
angularJS 中的two-way data binding.
查看>>
MediaPlayer简易应用
查看>>
Ubuntu上完美视频播放软件XBMC
查看>>
idea创建maven项目的一点关键
查看>>
python函数:递归
查看>>
nodejs
查看>>
DIV+CSS 斜线效果
查看>>
虚拟机访问共享空间的身份验证问题
查看>>
ble低功耗蓝牙GATT应用协议
查看>>
ThinkPHP的url简化
查看>>
List<T> 类相关排序
查看>>
Win2012R2 AD主域控登录密码忘记
查看>>
php增加自动刷新当前页面
查看>>
[阿里]逆序打印整数,要求递归实现
查看>>
TCP小结
查看>>