题目
给定一个未排序的整数数组,找出最长连续序列的长度、
要求算法的时间复杂度为O(n).
示例:
输入:[100, 4, 200, 1, 3, 2]
输出:4
解释:最长连续序列是[1, 2, 3, 4]。它的长度为4
思路
思路一
- 先由小到大进行排序
- 考虑三种情况:
- 前后相差1,则是连续序列
- 前后相等,循环continue
- 最后一个元素,break
代码
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))
原文地址:https://www.cnblogs.com/wemo/p/10522002.html
时间: 2024-10-17 16:27:14