Clean and easy understood c++ solution


  • 0
    W
    class Solution {
    public:
        vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
            vector<string> res;
            nums.push_back(upper + 1);
            // avoid insertion of lower which cost O(n)
            addRange(res, lower, nums.front() - 1);
            for(int i = 0; i < nums.size() - 1; i++)
                addRange(res, nums[i] + 1, nums[i + 1] - 1);
            return res;
        }
        
    private:
        void addRange(vector<string>& v, int lowerBound, int upperBound) {
            if(lowerBound == upperBound)
                v.push_back(to_string(lowerBound));
            else if(lowerBound < upperBound)
                v.push_back(to_string(lowerBound) + "->" + to_string(upperBound));
            // push_back nothing if when upperBound < lowerBount
        }
    };

Log in to reply
 

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