[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.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"]
.
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.
這道題讓我們給了我們一個單詞陣列,又給定了兩個單詞,讓我們求這兩個單詞之間的最小距離,限定了兩個單詞不同,而且都在陣列中。我最先想到的方法比較笨,我首先想的是要用雜湊表來做,建立每個單詞和其所有出現位置陣列的對映,但是後來想想,反正建立對映也要遍歷一遍陣列,我們還不如直接遍歷一遍陣列,直接把兩個給定單詞所有出現的位置分別存到兩個數組裡,然後我們在對兩個陣列進行兩兩比較更新結果,參見程式碼如下:
解法一:
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; } };
類似題目:
參考資料: