美文网首页
245. Shortest Word Distance III

245. Shortest Word Distance III

作者: Ysgc | 来源:发表于2020-12-03 04:58 被阅读0次

    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
    Note:
    You may assume word1 and word2 are both in the list.


    我的答案:感觉这道题挺无聊的,就是243再加一个if的情况

    class Solution {
    public:
        int shortestWordDistance(vector<string>& words, string word1, string word2) {
            int ans = INT_MAX;
            int len = words.size();
            
            if (word1 == word2) {
                int last = INT_MIN;
                for (int i=0; i<len; ++i) {
                    if (words[i] == word1) {
                        if (last != INT_MIN)
                            ans = min(ans, abs(i-last));
                        last = i;
                    }
                }
            }
            else {
                int last1 = INT_MIN;
                int last2 = INT_MIN;
                for (int i=0; i<len; ++i) {
                    // cout << ans << " - " << abs(last1-last2)) << endl;
                    if (words[i] == word1 or words[i] == word2) {
                        if (words[i] == word1) 
                            last1 = i;
                        if (words[i] == word2)
                            last2 = i;
                        if (last1 != INT_MIN and last2 != INT_MIN)
                            ans = min(ans, abs(last1-last2));
                    }
                }
            }
            
            return ans;
        }
    };
    

    Runtime: 12 ms, faster than 97.08% of C++ online submissions for Shortest Word Distance III.
    Memory Usage: 12.3 MB, less than 62.57% of C++ online submissions for Shortest Word Distance III.

    相关文章

      网友评论

          本文标题:245. Shortest Word Distance III

          本文链接:https://www.haomeiwen.com/subject/ciatwktx.html