One pass Java solution


  • 0
    V
    public class Solution {
        public int shortestDistance(String[] words, String word1, String word2) {
            int minDist = Integer.MAX_VALUE, one = -1, two = -1;
            for (int i = 0; i < words.length; i++) {
                if (words[i].equals(word1)) {
                    one = i;
                    if (two != -1) {
                        minDist = Math.min(minDist, one - two);
                    }
                } else if (words[i].equals(word2)) {
                    two = i;
                    if (one != -1) {
                        minDist = Math.min(minDist, two - one);
                    }
                }
            }
            return minDist;
        }
    }
    

Log in to reply
 

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