[LeetCode] 243. Shortest Word Distance 最短單詞距離


 

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

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

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

Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

 

這道題給了我們一個單詞數組,又給定了兩個單詞,讓求這兩個單詞之間的最小距離,限定了兩個單詞不同,而且都在數組中。博主最先想到的方法比較笨,是要用 HashMap 來做,建立每個單詞和其所有出現位置數組的映射,但是后來想想,反正建立映射也要遍歷一遍數組,還不如直接遍歷一遍數組,直接把兩個給定單詞所有出現的位置分別存到兩個數組里,然后再對兩個數組進行兩兩比較更新結果,參見代碼如下:

 

解法一:

class Solution {
public:
    int shortestDistance(vector<string>& words, string word1, string word2) {
        vector<int> idx1, idx2;
        int res = INT_MAX;
        for (int i = 0; i < words.size(); ++i) {
            if (words[i] == word1) idx1.push_back(i);
            else if (words[i] == word2) idx2.push_back(i);
        }
        for (int i = 0; i < idx1.size(); ++i) {
            for (int j = 0; j < idx2.size(); ++j) {
                res = min(res, abs(idx1[i] - idx2[j]));
            }
        }
        return res;
    }
};

 

上面的那種方法並不高效,其實需要遍歷一次數組就可以了,用兩個變量 p1,p2 初始化為 -1,然后遍歷數組,遇到單詞1,就將其位置存在 p1 里,若遇到單詞2,就將其位置存在 p2 里,如果此時 p1, p2 都不為 -1 了,那么更新結果,參見代碼如下:

 

解法二:

class Solution {
public:
    int shortestDistance(vector<string>& words, string word1, string word2) {
        int p1 = -1, p2 = -1, res = INT_MAX;
        for (int i = 0; i < words.size(); ++i) {
            if (words[i] == word1) p1 = i;
            else if (words[i] == word2) p2 = i;
            if (p1 != -1 && p2 != -1) res = min(res, abs(p1 - p2));
        }
        return res;
    }
};

 

下面這種方法只用一個輔助變量 idx,初始化為 -1,然后遍歷數組,如果遇到等於兩個單詞中的任意一個的單詞,再看 idx 是否為 -1,若不為 -1,且指向的單詞和當前遍歷到的單詞不同,更新結果,參見代碼如下:

 

解法三:

class Solution {
public:
    int shortestDistance(vector<string>& words, string word1, string word2) {
        int idx = -1, res = INT_MAX;
        for (int i = 0; i < words.size(); ++i) {
            if (words[i] == word1 || words[i] == word2) {
                if (idx != -1 && words[idx] != words[i]) {
                    res = min(res, i - idx);
                }
                idx = i;
            }
        }
        return res;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/243

 

類似題目:

Shortest Word Distance II

Shortest Word Distance III 

 

參考資料:

https://leetcode.com/problems/shortest-word-distance/

https://leetcode.com/problems/shortest-word-distance/discuss/66931/AC-Java-clean-solution

https://leetcode.com/problems/shortest-word-distance/discuss/66939/Java%3A-only-need-to-keep-one-index

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM