Java Solution with one for loop


  • 13
    Q
    public class Solution {
    public int shortestDistance(String[] words, String word1, String word2) {
        int ret = Integer.MAX_VALUE, index1 = -1, index2 = -1;
        for(int i = 0; i < words.length; i++) {
            if(words[i].equals(word1)) {
                index1 = i; 
                if(index2 >= 0) ret = Math.min(ret, i - index2);
            } else if(words[i].equals(word2)) {
                index2 = i;
                if(index1 >= 0) ret = Math.min(ret, i - index1);
            }
        }
        return ret;
    }
    }

  • 0

    Clever idea without using abs :-)


  • 0

    why try to avoid using abs?


  • 0
    A

    @雨日羽

    Abs is not necessary because it is clear whether word1's last index is larger or word2's last index is larger. If the word at the current index i is word1, then the "largest index of word 2 found so far" is surely smaller than i.


  • 1
    Z

    Nice idea with out using abs.
    A little bit change with index1 and index2 to get rid of the if statement
    The code runtime is 2ms.

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.