2018-10-31 leetcode Longest Consecutive Sequence Longest Consecutive SequenceO(n) Version - 40ms 123456789101112131415161718class Solution: def longestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ nums = set(nums) maxlen = 0 while nums: first = last = nums.pop() while first - 1 in nums: first -= 1 nums.remove(first) while last + 1 in nums: last += 1 nums.remove(last) maxlen = max(maxlen, last - first + 1) return maxlen O(n) Version - 44ms 123456789101112131415class Solution: def longestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ nums = set(nums) ret = 0 for x in nums: if x - 1 not in nums: y = x + 1 while y in nums: y += 1 ret = max(ret, y - x) return ret test code 1234In [66]: s = Solution(); t = s.longestConsecutive([100, 4, 200, 3, 1, 2])In [67]: tOut[67]: 4 leet code Newer Container With Most Water Older Trapping Rain Water