128. Longest Consecutive Sequence
Solution
- Find the smallest number in each sequence
- Get the length of the sequence by counting the number of larger numbers in the sequence
Complexity: O(n)def longestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ set_nums = set(nums) res = 0 for num in nums: if num - 1 in set_nums: continue length = 1 end = num while end + 1 in set_nums: length += 1 end += 1 res = max(length, res) return res
PREVIOUSInsert Interval
NEXTWord Search II