算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从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<String> 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];
}
}
上期推文: