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

Note:

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

    题目的大意是找到两个数组中相同元素的index和最小的元素。解法是将数组a的元素放入map中,值为key、index为value, 当数组b也出现同样的元素的时候,两个元素的index的和与当前的最小值判断,大就舍弃,小就更新最小值,并放入一个新的列表。
public static String[] findRestaurant(String[] list1, String[] list2) {
int min = Integer.MAX_VALUE;
List<String> result = new ArrayList<>();
HashMap<String,Integer> map = new HashMap<>();
for(int i = 0; i < list1.length; i++)
map.put(list1[i],i);
for(int i = 0; i < list2.length; i++)
{
if(map.containsKey(list2[i]))
{
int index = map.get(list2[i]);
if(i + index == min)
{
result.add(list2[i]);
}
else if(i + index < min)
{
result.clear();
result.add(list2[i]);
}
}
}
return result.toArray(new String[result.size()]); //这里将list转为数值
}

看了leetcode上面的Discuss其他用户的写法,上面的代码可以做一个小小的优化,

    public static String[] findRestaurant(String[] list1, String[] list2) {
int min = Integer.MAX_VALUE;
List<String> result = new ArrayList<>();
HashMap<String,Integer> map = new HashMap<>();
for(int i = 0; i < list1.length; i++)
map.put(list1[i],i);
for(int i = 0; i < list2.length; i++)
{
Integer index = map.get(list2[i]); /////
if(index != null && i + index <= min)
{
if(i + index < min)
{
result.clear(); //存在更小的值,就将列表清空
min = i + index;
}
result.add(list2[i]);
}
}
return result.toArray(new String[result.size()]); //这里将list转为数值
}

这是一个常规的题目,主要是需要注意的有以下几点

  • 在选择较小的值的时候,往往为min赋值一个最大的值,注意写法
  • 判断map是否包含某个key使用containsKey返回的为布尔类型,可以灵活使用Integer
  • 清空列表使用clear,注意列表转数组的用法,数组转列表使用Arrays.asList(a)
上一篇:JDBC数据源连接池(4)---自定义数据源连接池


下一篇:[NOIP 2014TG D1T3] 飞扬的小鸟