243. Shortest Word Distance (E)

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.


https://www.lintcode.com/problem/shortest-word-distance/description


我的答案:用兩個indexes追蹤兩個words,只有當(dāng)某個index變化的時候,才要重新計算一次

class Solution {
public:
    /**
     * @param words: a list of words
     * @param word1: a string
     * @param word2: a string
     * @return: the shortest distance between word1 and word2 in the list
     */
    int shortestDistance(vector<string> &words, string &word1, string &word2) {
        // Write your code here
        int index1 = INT_MAX;
        int index2 = INT_MAX;
        int ans = INT_MAX;
        
        int len = words.size();
        for (int i=0; i<len; ++i) {
            if (words[i] == word1 or words[i] == word2) {
                if (words[i] == word1)
                    index1 = i;
                if (words[i] == word2)
                    index2 = i;
                if (index1 != INT_MAX and index2 != INT_MAX)
                    ans = min(ans, abs(index1 - index2));
            }
        }
        
        return ans;
    }
};

Runtime: 16 ms, faster than 73.88% of C++ online submissions for Shortest Word Distance.
Memory Usage: 11.9 MB, less than 90.79% of C++ online submissions for Shortest Word Distance.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容