smj007

Untitled

Jun 18th, 2022 (edited)
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.89 KB | None | 0 0
  1. class Solution:
  2.     def longestConsecutive(self, nums):
  3.        
  4.         if not nums:
  5.             return 0
  6.        
  7.         nums.sort()
  8.         longest_streak = 0
  9.         current_streak = 1
  10.        
  11.         for index, num in enumerate(nums[:-1]):
  12.             # an important step here would be to avoid duplicates
  13.             if (nums[index] != nums[index+1]):
  14.                 if (nums[index] + 1 == nums[index+1]):
  15.                     current_streak += 1
  16.                 else:
  17.                     longest_streak = max(current_streak, longest_streak)
  18.                     current_streak = 1
  19.        
  20.         # very important step here since there could be cases
  21.         # where current streak could be every increasing and
  22.         # longest streak could not get a chance to be assigned
  23.         longest_streak = max(current_streak, longest_streak)
  24.        
  25.         return longest_streak
Add Comment
Please, Sign In to add comment