C++ version of min difference btw 2 sorted arrays


  • 0
    R

    Re: Java solution using minimum difference between 2 sorted arrays

    class Solution {
    public:
        int shortestDistance(vector<string>& words, string word1, string word2) {
            vector<int> w1occ;
            vector<int> w2occ;
            
            for(int i = 0; i < words.size(); ++i) {
                if(words[i] == word1) {
                    w1occ.push_back(i);
                }
                if(words[i] == word2) {
                    w2occ.push_back(i);
                }
            }
            
            int mn = words.size();
            int p1 =0, p2 = 0;
            while(p1 < w1occ.size() && p2 < w2occ.size()) {
                mn = min(abs(w1occ[p1] - w2occ[p2]), mn);
                if(w1occ[p1] < w2occ[p2]) {
                    p1++;
                } else {
                    p2++;
                }
            }
            return mn;
        }
    };
    

Log in to reply
 

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