用python写一个可以满足下列要求的程序“给定一个整数序列,请找出这个整数序列的中间数的值。”
时间: 2023-06-24 20:08:35 浏览: 45
以下是一种基于排序的实现方式:
```python
def find_median(nums):
nums.sort() # 先将整数序列升序排序
n = len(nums)
if n % 2 == 0: # 如果序列长度为偶数,中间数的值为中间两个数的平均值
return (nums[n // 2 - 1] + nums[n // 2]) / 2
else: # 如果序列长度为奇数,中间数的值为中间那个数的值
return nums[n // 2]
```
使用示例:
```python
nums = [1, 2, 3, 4, 5]
median = find_median(nums)
print(median) # 输出 3
nums = [1, 2, 3, 4]
median = find_median(nums)
print(median) # 输出 2.5
```
相关问题
python 给定一个未排序的整数数组,找出数字连续的最长序列
思路:
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$ 是输入数组的长度。它首先将数组转换为一个集合,以便更快地检查某个数字是否存在。然后,它遍历数组中的每个数字,如果该数字是一个连续序列的起点,则尝试向后查找更长的连续序列,并跟踪最长的序列的长度和起始数字。最后,它返回从起始数字开始的最长连续整数序列。如果输入数组为空,则返回一个空列表。