題目:
給定一個未排序的整數數組,找出最長連續序列的長度。 要求算法的時間復雜度為 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