Python solution with O(n)


  • 0
    K
    class Solution(object):
        def longestConsecutive(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            _max = 0
            _map = {}
            for i in xrange(len(nums)):
                num = nums[i]
                if num in _map:
                    continue
                num1 = _map.get(num-1, 0)
                num2 = _map.get(num+1, 0)
                _map[num] = _map[num-num1] = _map[num+num2] = num1 + num2 + 1
                if _map[num] > _max:
                    _max = _map[num]
            return _max
    

Log in to reply
 

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