feat(0128_longest-consecutive-sequence): add py3 solution

This commit is contained in:
Sangeeth Sudheer 2022-04-05 04:07:51 +05:30
parent ee2167f554
commit cb5e32d56d
3 changed files with 45 additions and 0 deletions

View File

@ -0,0 +1,21 @@
Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
You must write an algorithm that runs in `O(n)` time.
**Example 1:**
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
**Example 2:**
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`

View File

@ -0,0 +1,24 @@
# Time: O(NlogN)
# Space: O(1)
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
nums.sort()
max_length = 1
l = 1
# We don't want to go OOB
for i in range(0, len(nums) - 1):
diff = nums[i + 1] - nums[i]
# All good, still consecutive.
if diff == 1:
l += 1
max_length = max(max_length, l)
# We skip to next iteration of loop if
# item repeats. Otherwise, we reset
# running length variable to 1
elif diff != 0:
l = 1
return max_length if len(nums) > 0 else 0