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;
    }
}
                  
                  
                  
                  
                            
                            
本文介绍了一个算法,用于在给定数组中找到两个指定单词之间的最短距离。通过遍历数组并记录每个单词的位置,可以计算出两者的最小距离。
          
      
          
                
                
                
                
              
                
                
                
                
                
              
                
                
              
            
                  
					455
					
被折叠的  条评论
		 为什么被折叠?
		 
		 
		
    
  
    
  
            


            