C++ clean solution, mimic find_first_of()


  • 0
    C
        vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
            // inspired by the C++ first_first_of() function, use three ptrs, i, j and k
            int n = nums.size();
            long i = lower, j = lower, k = 0;
            vector<string> ans;
            
            while(k < n && i <= upper) { // while condition is used to take care of n == 0 edge case
                // find start of (1st) missing range 
                for(; k < n && i <= upper && nums[k] == i; i++, k++) {}
                // i is the start of missing range
                
                // find end of 1st missing range
                j = i + 1;
                for(; k < n && j <= upper && nums[k] != j; j = nums[k]) {}
                // j - 1 is the end of missing range
                
                if(k < n && j <= upper) {  // let us do another round
                    if(i == j - 1) ans.push_back(to_string(i));
                    else if(i < j - 1) ans.push_back(to_string(i) + "->" + to_string(j-1));
                    i = j;      
                } else { // no more round
                    break;
                }
            }
            // below take care of edge cases: "n == 0" or "k reached n after while"
            if(i == upper) ans.push_back(to_string(i));
            else if(i < upper) ans.push_back(to_string(i) + "->" + to_string(upper));
    
            return ans;
        }
    

Log in to reply
 

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