LeetCode-2つのリストの最小インデックス合計



Leetcode Minimum Index Sum Two Lists



説明:
AndyとDorisが夕食にレストランを選びたいと思っていて、どちらも文字列で表されたお気に入りのレストランのリストを持っているとします。

あなたは彼らが最小のリストインデックスの合計で彼らの共通の興味を見つけるのを助ける必要があります。回答の間に選択の同点がある場合は、順序を必要とせずにすべてを出力します。あなたは常に答えが存在すると仮定することができます。



例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'.

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

注意:

  • 両方のリストの長さは[1、1000]の範囲になります。
  • 両方のリストの文字列の長さは[1、30]の範囲になります。
  • インデックスは0から始まり、リストの長さから1を引いたものです。
  • 両方のリストに重複はありません。

意図:2つの文字列の配列を計算するパブリック文字列。複数の文字列が含まれている可能性がありますが、下付き文字の位置とこれらのパブリック文字列の最小値(配列内)が必要です。

解決策:2つの文字列配列に添え字の位置とこれらのパブリック文字列の最小値を必要とするピットがあります。実際、2つのケースしかありません。



  1. 返される結果には文字列が1つだけ含まれます
  2. 返される結果には、2つの文字列配列で添え字の位置が同じである複数の文字列が含まれています

ハッシュテーブルを使用して、最初の文字列配列とその添え字の位置にあるすべての文字列を記録し、2番目の文字列配列をトラバースした後、計算プロセスは次のようになります。

for str in list2: There is no str in the if hash table: Judge the next string If str is the first public string found: Add str to the result string array res and record the subscript position and indexSum at this time Elif the current subscript position of the string and
Java
class Solution { public String[] findRestaurant(String[] list1, String[] list2) { StringBuilder res = new StringBuilder() int indexSum = -1 Map map = new HashMap() int ind = 0 for (String str: list1) { map.put(str, ind) ind++ } ind = 0 for (String str: list2) { if (!map.containsKey(str)) { ind++ continue } int tempSum = map.get(str) + ind if (indexSum == -1) { indexSum = tempSum res.append(str) } else if (tempSum