Sunday, August 08, 2021

Leetcode 128 Longest Consecutive Sequence

 In here, I would like to discuss the dynamic set in Leetcode 128 Longest Consecutive Sequence.

This is my solution: 

  • Put all numbers into set.
  • The find the first number of each sequence. The first number is the number without any previous number (n-1) in the set.
  • Loop through the next number (n+1). And find out the max count. (Remove the current number from set in order to iterate it again.)


var longestConsecutive = function(nums) {
    
    let set = new Set(nums);
    let maxLen = 0;
    function next(num) {
        if (set.has(num)) {
            //set.delete(num);
            return next(num + 1) + 1;
        } else {
            return 0;
        }
    }
    console.log(set);
    for (let num of nums) {
        //console.log(num);
        let pre = num - 1;
        if (!set.has(pre)) {
            let len = next(num+1) + 1;
            if (len > maxLen) {
                maxLen = len;
            }
        }
    }

    return maxLen;
};

 

The particular I would discuss is 

Remove the current number from set in order to iterate it again.

set.delete(num)

I would say that can be optimize performance. However, base on the leetcode submission result, dynamic changing set is actually a performance penalty.



 

 

 

 

 

 

No comments: