Efficient C++ solution 19ms


  • 0
    D

    In this solution, I use 2 pointers to move from begin to end position.

            int pt1,pt2, min_val;
            pt1 = pt2 = min_val = 0;
            while(pt1 < words.size() && pt2 < words.size()){
                if(words[pt1] != word1 && words[pt2] != word2){
                    pt1++; pt2++;
                    continue;
                }
    
                if((words[pt1] == word1 && words[pt2] == word1)){
                    pt1 = std::max(pt1, pt2);
                    pt2 = pt1 + 1;
                    continue;
                }
    
                if((words[pt1] == word2 && words[pt2] == word2)){
                    pt2 = std::max(pt1, pt2);
                    pt1 = pt2 + 1;
                    continue;
                }
    
                if(words[pt1] == word1 && words[pt2] == word2){
                    min_val = std::min(min_val, std::abs(pt2-pt1));
                    if(min_val == 1) return min_val;
                    if(pt2 > pt1){
                        pt1 = pt2+1;
                    }else{
                        pt2 = pt1+1;
                    }
                    continue;
                }
    
                if(words[pt1] == word1){
                    ++pt2;
                    continue;
                }
    
                if(words[pt2] == word2){
                    ++pt1;
                    continue;
                }
            }
            return  min_val;
        }```

Log in to reply
 

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