[LC] 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.

 

Solution1:

O(N^2)

class Solution {
    public int shortestDistance(String[] words, String word1, String word2) {
        int res = words.length; 
        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(word1)) {
                for (int j = 0; j < words.length; j++) {
                    if (words[j].equals(word2)) {
                        res = Math.min(res, Math.abs(i - j));
                    }
                }
            }
        }
        return res;
    }
}

 

 

Solution2:

O(N)

class Solution {
    public int shortestDistance(String[] words, String word1, String word2) {
        int res = words.length;
        int s1 = -1, s2 = -1;
        for (int i = 0; i < words.length; i++) {
            String cur = words[i];
            if (cur.equals(word1)) {
                s1 = i;
            } else if (cur.equals(word2)) {
                s2 = i;
            }
            if (s1 != -1 && s2 != -1) {
                res = Math.min(res, Math.abs(s1 - s2));
            }
        }
        return res;
    }
}

 

posted @ 2019-11-18 05:05  xuan_abc  阅读(124)  评论(0编辑  收藏  举报