Leetcode练习(Python):数组类:第128题:给定一个未排序的整数数组,找出最长连续序列的长度。 要求算法的时间复杂度为 O(n)。
题目:
给定一个未排序的整数数组,找出最长连续序列的长度。 要求算法的时间复杂度为 O(n)。
思路:
要求的时间复杂度为O(n),则只允许一次循环。
程序:
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
nums.sort()
length = len(nums)
if length <= 0:
return 0
if length == 1:
return 1
max_count = 1
counter = 1
for index in range(1,length):
if nums[index - 1] == nums[index]:
continue
if nums[index - 1] < nums[index] and nums[index] - nums[index - 1] == 1:
counter += 1
max_count = max(max_count, counter)
else:
counter = 1
continue
return max_count