python 给定一个未排序的整数数组,找出数字连续的最长序列
时间: 2024-05-03 16:21:40 浏览: 14
思路:
1. 先将数组排序。
2. 遍历排序后的数组,记录当前连续序列的起始和终止位置。
3. 如果当前数字与前一个数字连续,则更新终止位置。
4. 如果当前数字与前一个数字不连续,则更新起始位置。
5. 每遍历一个数字,都更新最长连续序列的长度和起始位置。
代码实现:
```python
def longestConsecutive(nums):
if not nums:
return 0
nums.sort()
start = end = res = 1
for i in range(1, len(nums)):
if nums[i] == nums[i-1]+1:
end += 1
elif nums[i] == nums[i-1]:
continue
else:
res = max(res, end-start+1)
start = end = i
return max(res, end-start+1)
```
测试:
```
>>> nums = [100, 4, 200, 1, 3, 2]
>>> longestConsecutive(nums)
4
```
时间复杂度:排序的时间复杂度为$O(nlogn)$,遍历一次数组的时间复杂度为$O(n)$,因此总时间复杂度为$O(nlogn)$。
相关问题
python 给定一个未排序的整数数组,找出数字连续的最长序列并且打印出列表
以下是一个可能的解决方案:
```python
def longestConsecutive(nums):
if not nums:
return []
nums_set = set(nums)
max_len = 0
start = None
for num in nums:
if num - 1 not in nums_set:
curr_len = 1
curr_start = num
while curr_start + 1 in nums_set:
curr_len += 1
curr_start += 1
if curr_len > max_len:
max_len = curr_len
start = num
return list(range(start, start + max_len))
# 示例用法
nums = [100, 4, 200, 1, 3, 2]
print(longestConsecutive(nums)) # 输出 [1, 2, 3, 4]
```
该函数的时间复杂度为 $O(n)$,其中 $n$ 是输入数组的长度。它首先将数组转换为一个集合,以便更快地检查某个数字是否存在。然后,它遍历数组中的每个数字,如果该数字是一个连续序列的起点,则尝试向后查找更长的连续序列,并跟踪最长的序列的长度和起始数字。最后,它返回从起始数字开始的最长连续整数序列。如果输入数组为空,则返回一个空列表。
给定一个未排序的整数数组,找出数组连续的最长的序列并且打印列表
思路:先将数组排序,然后遍历数组,统计当前连续序列的长度和起始数字,如果当前数字不是上一个数字的后继,则当前连续序列结束,比较当前连续序列长度和最长连续序列长度,如果当前连续序列更长,则更新最长连续序列的长度和起始数字。
代码如下:
```python
def longestConsecutive(nums):
if not nums:
return []
nums.sort()
max_len = 1
cur_len = 1
start = nums[0]
res = [start]
for i in range(1, len(nums)):
if nums[i] == nums[i-1] + 1:
cur_len += 1
elif nums[i] != nums[i-1]:
if cur_len > max_len:
max_len = cur_len
res = list(range(start, start+max_len))
cur_len = 1
start = nums[i]
if cur_len > max_len:
res = list(range(start, start+cur_len))
return res
```
测试:
```python
print(longestConsecutive([100, 4, 200, 1, 3, 2])) # [1, 2, 3, 4]
print(longestConsecutive([1, 2, 0, 1])) # [0, 1, 2]
```