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.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = “coding”, word2 = “practice”, return 3.
Given word1 = "makes", word2 = "coding", return 1.
题意:给定一个数组和两个单词word1,word2,返回两者最近的距离
word1不等于word2,但是两者可能在数组中出现多次
分类:数组
解法1:遍历数组,当遍历到word1,word2,记录下位置,并且每次都计算最新的最小值
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;
}
}