Share my O(n) C++ solution


  • 1
    J

    class Solution {

    public:

    int shortestDistance(vector<string>& words, string word1, string word2) 
    
    {
        int pos1,pos2;
        bool flag1 = false;
        bool flag2 = false;
        int min = words.size();
     for(int i=0;i<words.size();i++)
     {
         if(words[i]==word1)
         {
             pos1 =i;
             flag1 = true;
         }
         if(words[i]==word2)
         {
             pos2 = i;
             flag2 = true;
         }
         if(flag1==true && flag2 == true)
         {  
    
             if(abs(pos1-pos2)<min)
             {
             min= abs(pos1-pos2);
                 
             }
         }
     } 
     return min;
    }
    

    };


  • 0

    @Jason_Mu_Genius This is a simple straightforward way. There is an improvement to spare the declaration of the two boolean flags. You can simply default to a negative index for pos1 and pos2, so updating the minimum distance, you can check if (pos1 >= 0 && pos2 >= 0).


Log in to reply
 

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