1. 程式人生 > >245. Shortest Word Distance III 單詞可以重復的最短單詞距離

245. Shortest Word Distance III 單詞可以重復的最短單詞距離

距離 list NPU ring example 一次 技術分享 open 處理

[抄題]:

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

word1 and word2 may be the same and they represent two individual words in the list.

Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Input: word1
= “makes”, word2 = “coding” Output: 1
Input: word1 = "makes", word2 = "makes"
Output: 3

[暴力解法]:

把word1所有的index存一個數組,把word2所有的index存一個數組,再i*j全部掃一遍

時間分析:n^2

空間分析:

[優化後]:

每次走一個index都隨時更新一下i1 i2

時間分析:n

空間分析:

[奇葩輸出條件]:

[奇葩corner case]:

雖然不麻煩,但是Integer.MAX_VALUE 必須要存成long型,然後轉回來就行了。不然會報錯。

[思維問題]:

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

[一句話思路]:

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

[畫圖]:

技術分享圖片

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

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

[總結]:

p1 p2相等的時候,暫存一下之前的p2

if (word1.equals(word2)) 
                    //store in p1 temporarily
                    p1 = p2;
                 p2 = i; 

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

[算法思想:叠代/遞歸/分治/貪心]:

[關鍵模板化代碼]:

[其他解法]:

[Follow Up]:

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

[代碼風格] :

[是否頭一次寫此類driver funcion的代碼] :

[潛臺詞] :

技術分享圖片
class Solution {
    public int shortestWordDistance(String[] words, String word1, String word2) {
        //ini: p1, p2 into the long type
        long result = Integer.MAX_VALUE;
        long p1 = Integer.MAX_VALUE;
        long p2 = -Integer.MAX_VALUE;
        
        
        //for loop: for each words[i], renew the answer
        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(word1)) p1 = i;
            if (words[i].equals(word2)) 
                {
                if (word1.equals(word2)) 
                    //store in p1 temporarily
                    p1 = p2;
                 p2 = i; 
            }  
            //renew the answer
            result = Math.min(result, Math.abs(p2 - p1));
        }
        
        //return
        return (int)result;
    }
}
View Code

245. Shortest Word Distance III 單詞可以重復的最短單詞距離