Java O(n) solution


  • 0
    M
    public class Solution {
        public int shortestDistance(String[] words, String word1, String word2) {
            int a = Integer.MAX_VALUE, b = a;
            int dis = a, min = a;
            for(int i=0; i<words.length; i++){
                if(words[i].equals(word1)) {
                    a = i;
                    dis = Math.abs(a-b);
                } else if(words[i].equals(word2)) {
                    b = i;
                    dis = Math.abs(a-b);
                }
                min = Math.min(min, dis);
            }
            return min;
        }
    }
    
    

Log in to reply
 

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