2ms Easy to understand Java solution, beats 99.70%!


  • 0
    M

    The code is clean and easy to understand, I wrote this because I saw some others' solution keep comparing the current distance with the min distance, which is kinda waste of time, so I come up with an idea to just compare when needed.

    public class Solution {
        public int shortestDistance(String[] words, String word1, String word2) {
            int idx1 = -1, idx2 = -1;
            int dis = Integer.MAX_VALUE;
            for(int i = 0; i < words.length; i++) {
                String word = words[i];
                if(idx1 * idx2 <= 0) {
                    // either found
                    if(word1.equals(word)) {
                        // word1 found
                        idx1 = i;
                        dis = Math.min(dis, idx1 - idx2);
                        idx2 = -1; // set word2 not found
                    }
                    if(word2.equals(word)) {
                        // word2 found
                        idx2 = i;
                        dis = Math.min(dis, idx2 - idx1);
                        idx1 = -1; // set word1 not found
                    }
                }
                else {
                    // neither found
                    if(word1.equals(word)) idx1 = i;
                    if(word2.equals(word)) idx2 = i;
                }
            }
            return dis; 
        }
    }
    

Log in to reply
 

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