Easy python solution


  • 0
    L

    Here is an easy solution, I think it's easy to understand too.

    class Solution:
    # @param num, a list of integer
    # @return an integer
    def longestConsecutive(self, num):
        cache={};
        for n in num:
            cache[n]=1;
            
        longest=1;
        for n in num:
            cn=1;
            prev=n-1;
            while(prev in cache):
                del cache[prev]
                prev-=1;
                cn+=1;
            next=n+1;
            while(next in cache):
                del cache[next];
                next+=1;
                cn+=1;
            
            if(cn>longest):
                longest=cn; 
        return longest;

  • 0
    K

    what if there is negative number in initial array?


  • 0
    L

    it doesn't matter, because we only care +1, -1.


Log in to reply
 

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