Tuesday, September 9, 2014

Leetcode: Longest Consecutive Sequence @Python

class Solution:
    # @param num, a list of integer
    # @return an integer
    def longestConsecutive(self, num):
        dict={x:False for x in num}
        maxlen=0
        for i in num:
            if dict[i]==False:
                dict[i]=True
                crt=i+1
                len1=0
                while crt in dict:
                    dict[crt]=True;crt+=1;len1+=1
                crt=i-1;len0=0
                while crt in dict:
                    dict[crt]=True;crt-=1;len0+=1
                maxlen=max(maxlen, 1+len0+len1)
        return maxlen

No comments :

Post a Comment