題目來源:
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.
題意:給定一個數組和兩個單詞word1,word2,返回兩者最近的距離word1不等於word2,但是兩者可能在數組中出現多次
題目分析:
本題可以考慮在遍歷數組的時候記錄word1,word2的位置,並且每次都計算最新的最小值。
由於本題需要解鎖才能提交,這樣這裏我直接拷貝別人的java代碼:
public class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
if (words == null) return -1;
int idx1 = -1, idx2 = -1;
int diff = words.length;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1)) {
idx1 = i;
} else if (words[i].equals(word2)) {
idx2 = i;
}
if(idx1!=-1&&idx2!=-1){
diff = Math.min(diff,Math.abs(idx1-idx2));
}
}
return diff;
}
}