599.两个表格的最小索引加起来(javascript)599.MinimumIndexSumofTwoLists

原创
小哥 3年前 (2022-11-11) 阅读数 2 #大杂烩

假设 Andy 和 Doris 我想选择一家餐馆吃饭,他们都有一份最喜欢的餐馆名单。每个餐厅的名称由字符串表示。

你需要用最少的索引帮助他们,找出他们最喜欢的餐馆。 如果有多个答案,则输出所有答案,而不考虑顺序。 你可以假设答案总是存在的。

Given two arrays of strings list1 and list2, find the common strings with the least index sum.

A common string is a string that appeared in both list1 and list2.

A common string with the least index sum is a common string such that if it appeared at list1[i] and list2[j] then i + j should be the minimum value among all the other common strings.

Return all the common strings with the least index sum. Return the answer in any order.

示例 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)。

提示:

1 <= list1.length, list2.length <= 1000
1 <= list1[i].length, list2[i].length <= 30
list1[i] 和 list2[i] 由空格 ’ ’ 还有英文字母。
list1 所有字符串都是 唯一 的。
list2 中所有字符串都是 唯一 的。

根据题意
num 设置初始值,向上 len1 + len2

  1. 将list1指数和价值map(newMap )中
  2. 对list2仅横向移动newMap 操作中有数据。
  3. 获取两个索引和。 数组和中相同字符串的索引。
  4. 当i + j < num,res 重置 [];num 重新赋值i + j,存储字符串
  5. 当i + j == num 存储字符串

    /**

    • @param {string[]} list1
    • @param {string[]} list2
    • @return {string[]} */ var findRestaurant = function (list1, list2) { let len1 = list1.length, len2 = list2.length; let newMap = new Map() for (let i = 0; i < len1; i++) { newMap.set(list1[i], i) } let res = [] let num = len1 + len2 for (let i = 0; i < len2; i++) { if (newMap.has(list2[i])) { let j = newMap.get(list2[i]) if (i + j < num) { res = []; num = i + j res.push(list2[i]) } else if (i + j == num) { res.push(list2[i]) } else { break } } } return res };

leetcode : https://leetcode.cn/problems/minimum-index-sum-of-two-lists/

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除