Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Store all numbers in a hash map for O(1) existence checking.
- For each number, only start counting if it is the beginning of a sequence (i-1 is missing).
- Then expand forward (i, i+1, i+2...) while numbers exist in the map and track the length.
- The maximum length found across all starts is the longest consecutive sequence.
- Trick:
- When you start checking the longest consecutive elements, check for all the elements of the map because array can have a lot of the duplicates.
- """
- class Solution:
- def longestConsecutive(self, nums: List[int]) -> int:
- dict={}
- for i in nums:
- dict[i]=dict.get(i,0)+1
- ans=0
- for i in dict.keys():
- ele=i
- if dict.get(ele-1,0)==0:
- cur=0
- while dict.get(ele,0)!=0:
- cur+=1
- ele+=1
- if cur>ans:
- ans=cur
- return ans
Advertisement
Add Comment
Please, Sign In to add comment