最长连续序列,使用python实现
时间: 2024-01-01 12:05:29 浏览: 48
以下是使用Python实现最长连续序列的示例代码:
```python
def longest_consecutive(nums):
# 将列表转换为集合,以提高查找效率
num_set = set(nums)
max_length = 0
for num in num_set:
# 只考虑当前数字是一个序列的起点,即前一个数字不存在于集合中
if num - 1 not in num_set:
current_num = num
current_length = 1
# 继续查找下一个连续数字
while current_num + 1 in num_set:
current_num += 1
current_length += 1
# 更新最长连续序列的长度
max_length = max(max_length, current_length)
return max_length
```
你可以使用这个函数来计算给定列表中的最长连续序列的长度。例如:
```python
nums = [100, 4, 200, 1, 3, 2]
result = longest_consecutive(nums)
print(result) # 输出: 4
```
在上面的示例中,给定的列表为 `[100, 4, 200, 1, 3, 2]`,其中最长的连续序列是 `[1, 2, 3, 4]`,因此返回结果为 4。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)