163. Missing Ranges

class Solution {
public:
    vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
        if (nums.empty())
            return {builtFormat(lower, upper)};
        vector<string> res;
        if (nums[0] != lower)
            res.push_back(builtFormat(lower, nums[0] - 1));
        for (int i = 0; i < nums.size() - 1; i++)
            if (long(nums[i + 1]) - long(nums[i]) >= 2)    //attention to overflow!!!
                res.push_back(builtFormat(nums[i] + 1, nums[i + 1] - 1));
        if (nums[nums.size() - 1] != upper)
            res.push_back(builtFormat(nums[nums.size() - 1] + 1, upper));
        return res;
    }
private:
    string builtFormat(int i, int j) {
        if (i == j) return to_string(i);
        return to_string(i) + "->" + to_string(j);
    }
};

results matching ""

    No results matching ""