c++ solutions O(N)


  • 0
    D
    public:
        vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
            int n = nums.size();
            vector<string> ans;
            if(n==0){
                ans.push_back(to_string(lower) + (lower==upper?"":"->"+to_string(upper)));
                return ans;
            }//corner case for empty vector
           
            
            if(nums[0] > lower){
                int c = nums[0]-1;
                string s = to_string(lower) +  (c==lower?"":"->"+to_string(c));
                ans.push_back(s);
            } //add some range is the lower is smaller than the first item in the array
            
            nums.push_back(upper+1);   //since I want to get the upper is bigger than the last item in to the loop.
            
            for(int i = 0; i < n; ++i){
                string s;
                int a = nums[i] + 1;
                int b = nums[i+1] -1;
                a = (a>=lower)? a:lower;
                b = (b<=upper)? b:upper;
                if(a>b)
                    continue;  //this is for the case nums[i] and nums[i+1] are consecutive numbers.
                s = to_string(a) + (a==b?"":"->" + to_string(b));
                ans.push_back(s);
                if(nums[i+1]-1 == upper) //if the last item and upper are consecutive.
                    break;
                
            }
            return ans;
        }
    };

Log in to reply
 

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