1. 程式人生 > >599. Minimum Index Sum of Two Lists兩個餐廳列表的索引和最小

599. Minimum Index Sum of Two Lists兩個餐廳列表的索引和最小

ins 條件 ner 模板 還要 order PE ioc form

[抄題]:

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

[暴力解法]:

時間分析:

空間分析:

[優化後]:

時間分析:

空間分析:

[奇葩輸出條件]:

[奇葩corner case]:

兩次求和的長度有可能相等,都是最大,需要直接往結果裏添加

[思維問題]:

以為要存兩個hashset。但其實直接取,判斷是否為空即可,能少存一次

[一句話思路]:

存一次,取一次

[輸入量]:空: 正常情況:特大:特小:程序裏處理到的特殊情況:異常情況(不合法不合理的輸入):

[畫圖]:

[一刷]:

  1. 有新的最小值之和時,記得實時更新

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分鐘肉眼debug的結果]:

[總結]:

存一次,取一次

[復雜度]:Time complexity: O(n) Space complexity: O(n)

[英文數據結構或算法,為什麽不用別的數據結構或算法]:

res.toArray(new String[res.size()]) list變成數組,裏面再放字符串,字符串還要指定大小。轉了3次。

直接指定string的尺寸:用括號

[關鍵模板化代碼]:

[其他解法]:

[Follow Up]:

[LC給出的題目變變變]:

[代碼風格] :

技術分享圖片
class Solution {
    public String[] findRestaurant(String[] list1, String[] list2) {
        //ini: hashmap, linkedlist
        Map<String, Integer> map = new HashMap<>();
        List<String> res = new LinkedList<>();
        int minSum = Integer.MAX_VALUE;
        
        //put list1 into hashmap
        for (int i = 0; i < list1.length; i++) {
            map.put(list1[i], i);
        }
        
        //get from list2
        for (int i = 0; i < list2.length; i++) {
            Integer j = map.get(list2[i]);
            if (j != null && i + j <= minSum) {
                if (i + j < minSum) {
                    res.clear();
                    minSum = i + j;
                }
                    res.add(list2[i]);
            }
        }
        
        //return, change form
        return res.toArray(new String[res.size()]);
    }
}
View Code

599. Minimum Index Sum of Two Lists兩個餐廳列表的索引和最小