LeetCode 솔루션 분류
[7/5] 128. Longest Consecutive Sequence
본문
Medium
11658500Add to ListShareGiven 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
관련자료
-
링크
댓글 1
학부유학생님의 댓글
- 익명
- 작성일
# O(n) Solution
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
nums = set(nums)
max_len = 0
while nums:
inc = dec = nums.pop()
while inc + 1 in nums:
inc += 1
nums.remove(inc)
while dec - 1 in nums:
dec -= 1
nums.remove(dec)
max_len = max(max_len, inc - dec + 1)
return max_len
# O(nlogn) solution
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
nums = sorted(list(set(nums)))
consequtive_num = 1
max_consequtive_num = 1
for i in range(1, len(nums)):
if (nums[i] == nums[i-1] + 1):
consequtive_num += 1
else:
consequtive_num = 1
max_consequtive_num = max(max_consequtive_num, consequtive_num)
return 0 if len(nums)==0 else max_consequtive_num