Clear JavaScript O(nums) solution


  • 0
    var findMissingRanges = function(nums, lower, upper) {
        nums = [...new Set(nums)];  // filter out duplicates
        const res = [buildInt(lower, upper)];
        
        for (let k of nums) {
            let lastInt = res[res.length - 1];
            let arrow = lastInt.indexOf('->');
            
            if (~arrow) {
                let open = parseInt(lastInt.substr(0, arrow));
                let close = parseInt(lastInt.substr(arrow + 2));
                
                if (k === open) {
                    res[res.length - 1] = buildInt(k + 1, close);
                } else {
                    res[res.length - 1] = buildInt(open, k - 1);
                    if (k < close) res.push(buildInt(k + 1, close));
                }
            } else if (k === parseInt(lastInt)) {
                res.pop();
            }
        }
        
        return res;
    };
    
    function buildInt(open, close) {
        return open === close ? '' + open : open + '->' + close;
    }
    

    The basic idea here is to keep splitting the last interval at nums[i].

    Here is a much cleaner solution by @linfongi.


Log in to reply
 

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