JavaScript solution with O(N)


  • 0
    S

    var longestConsecutive = function(nums) {

    var map = {};
    nums.forEach(function(num){
        map[num] = 1;
    });
    var result = 0;
    nums.forEach(function(num){
        var up = num + 1;
        while(map[up]){
            delete map[up];
            up++;
        }
        var down = num -1;
        while(map[down]){
             delete map[down];
             down--;
        }
        result = Math.max(result, up-down-1);
    });
    return result;
    

    };


  • 0
    W
    This post is deleted!

  • 0
    S

    you need to delete the item from hash array after it has been counted for the maxlength, other wise your algorithm's time complexity will be O(N*2)


Log in to reply
 

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