C# - O(n) almost the same as Shortest Word Distance 1


  • 0

    This problem is nearly the same as the first problem

    the only difference is this line

        if (words[i] == word2) index2 = i;
    

    the rest is the same. Here it is:

        public int ShortestWordDistance(string[] words, string word1, string word2) 
        {
            int index1 = -words.Length;
            int index2 = -words.Length;
            int min = words.Length;
            
            for (int i = 0; i < words.Length; i++)
            {
                if (words[i] == word1)
                {
                    index1 = i;
                    min = index1 - index2 < min ? index1 - index2 : min;
                    if (words[i] == word2) index2 = i;
                }
                else if (words[i] == word2)
                {
                    index2 = i;
                    min = index2 - index1 < min ? index2 - index1 : min; 
                }
            }
            
            return min;
        }
    

Log in to reply
 

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