Given a list of words and two wordsword1andword2, return the shortest distance between these two words in the list.
For example,
Assume that words =["practice", "makes", "perfect", "coding", "makes"].
Givenword1=“coding”,word2=“practice”, return 3.
Givenword1="makes",word2="coding", return 1.
Note:You may assume thatword1does not equal toword2, andword1andword2are both in the list.
min的計算放到if里大大減少判斷次數(shù), 也提高了運(yùn)行效率。
public int shortestDistance(String[] words, String word1, String word2) {
? ? ? ?int pos1 = -1;
? ? ? ?int pos2 = -1;
? ? ? ?int min = Integer.MAX_VALUE;
? ? ? ?for(int i = 0; i < words.length; i++){
? ? ? ? ? ? ? ? if(words[i].equals(word1)){
? ? ? ? ? ? ? ? ? ? ? ?pos1 = i;
? ? ? ? ? ? ? ? ? ? ? ?if(pos1 != -1 && pos2 != -1){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?min = Math.min(min, Math.abs(pos1 - pos2));
? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ?}else if(words[i].equals(word2)){
? ? ? ? ? ? ? ? ? ? ? ? pos2 = i;
? ? ? ? ? ? ? ? ? ? ? ? if(pos1 != -1 && pos2 != -1){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? min = Math.min(min, Math.abs(pos1 - pos2));
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ?}
? ? ? ?}
? ? ? ?return min;
}