Simply 0ms C++ solution


  • 11
    C
    class Solution {
    public:
        string get_range(int start, int end)
        {
            return start==end? to_string(start) : to_string(start)+"->"+to_string(end);
        }
        vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
            vector<string> result;
            int pre = lower-1;
            for(int i =0; i <= nums.size(); i++)
            {
               int cur = (i==nums.size()? upper+1:nums[i]);
               if(cur-pre>=2)
                result.push_back(get_range(pre+1,cur-1));
                pre = cur;
            }
            return result;
        }
    };

  • 0
    S

    Nice, mine is almost the same as yours


  • 0
    Z

    I like your code, very concise and neat! It's more like two pointers


  • 1
    F

    should consider INT_MIN


  • 0
    X

    @finalspace Yes. it overflows.


  • 1
    I

    @chaaarr
    Guess it doesn't work for the case [INT_MIN, INT_MAX]?
    the branching sentence if(cur-pre>=2) would fail on that due to overflow.


  • 0
    Q
    This post is deleted!

  • 0
    A

    Your code should be modified for the new cases.

    class Solution {
    public:
        string get_range(int start, int end)
        {
            return start==end? to_string(start) : to_string(start)+"->"+to_string(end);
        }
        vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
            vector<string> result;
            long int pre = (long)lower-1;
            if(nums.size()<=0)
            {
                result.push_back(get_range(lower,upper));
                return result;
            }   
            for(int i =0; i <= nums.size(); i++)
            {
               long int cur = (i==nums.size()? (long)upper+1:(long)nums[i]);
               if(cur-pre>=2)
                result.push_back(get_range(pre+1,cur-1));
                pre = cur;
            }
            return result;
        }
    };
    

  • 0
    H
    string getRange(int start, int end){
            return start == end ? to_string(start) : to_string(start) + "->" + to_string(end);
        }
        vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
            vector<string> result;
            long int pre = (long) lower - 1;
            
            for(int i = 0; i <= nums.size(); i++){
                long int cur = i == nums.size() ? (long) upper+1 : (long) nums[i];
                if(cur - pre >= 2)
                    result.push_back(getRange(pre+1, cur-1));
                pre = cur;
                
            }
            
            return result;
        }

Log in to reply
 

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