feat(0128_longest-consecutive-sequence): add py3 solution
This commit is contained in:
parent
ee2167f554
commit
cb5e32d56d
21
0128_longest-consecutive-sequence/README.md
Normal file
21
0128_longest-consecutive-sequence/README.md
Normal 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`
|
24
0128_longest-consecutive-sequence/python3/nlogn.py
Normal file
24
0128_longest-consecutive-sequence/python3/nlogn.py
Normal 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
|
Loading…
Reference in New Issue
Block a user