标签:.so enum sort 整数 最大 seq for i+1 int
给定一个未排序的整数数组,找出最长连续序列的长度、
要求算法的时间复杂度为O(n).
示例:
输入:[100, 4, 200, 1, 3, 2]
输出:4
解释:最长连续序列是[1, 2, 3, 4]。它的长度为4
def longestConsecutive(nums) -> int:
????if nums:
????????nums.sort()
????????#print(nums)
????????ans = [] #储存最大序列
????????max_seq = 1
????????for i, val in enumerate(nums):
????????????#print("序号:%s 值:%s"%(i, val)) 序号从零开始
????????????if(i == len(nums) - 1):
????????????????ans.append(max_seq)
????????????????break;
????????????if(nums[i] == nums[i+1]):
????????????????continue
????????????if(nums[i] - nums[i+1] == -1):
????????????????max_seq += 1
????????????else:
????????????????ans.append(max_seq)
????????????????max_seq = 1
????????return max(ans)
????else:
????????return 0
if __name__ == "__main__":
????nums = [100, 4, 200, 1, 3, 2]
????print(longestConsecutive(nums))
标签:.so enum sort 整数 最大 seq for i+1 int
原文地址:https://www.cnblogs.com/wemo/p/10522002.html