[LeetCode] 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.html

For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].java

Given word1 = 「coding」word2 = 「practice」, return 3.
Given word1 = "makes"word2 = "coding", return 1.數組

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

 

這道題讓咱們給了咱們一個單詞數組,又給定了兩個單詞,讓咱們求這兩個單詞之間的最小距離,限定了兩個單詞不一樣,並且都在數組中。我最早想到的方法比較笨,我首先想的是要用哈希表來作,創建每一個單詞和其全部出現位置數組的映射,可是後來想一想,反正創建映射也要遍歷一遍數組,咱們還不如直接遍歷一遍數組,直接把兩個給定單詞全部出現的位置分別存到兩個數組裏,而後咱們在對兩個數組進行兩兩比較更新結果,參見代碼以下:url

 

解法一:spa

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了,那麼咱們更新結果,參見代碼以下:code

 

解法二:htm

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,且指向的單詞和當前遍歷到的單詞不一樣,咱們更新結果,參見代碼以下:blog

 

解法三:leetcode

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;
    }
};

 

相似題目:

Shortest Word Distance II

Shortest Word Distance III 

 

參考資料:

https://leetcode.com/discuss/50234/ac-java-clean-solution

https://leetcode.com/discuss/61820/java-only-need-to-keep-one-index

 

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

相關文章
相關標籤/搜索