对于给定的含有n个整数的无序序列,求这个序列中最大和次大的两个不同的元素。python
时间: 2024-09-20 15:02:55 浏览: 52
DP、二分-LeetCode300. 最长上升子序列(Python)
在Python中,我们可以使用堆数据结构来解决这个问题。这里是一个基于两堆(最大堆和最小堆)的解决方案:
```python
import heapq
def max_two(nums):
# 最大值堆
max_heap = []
# 初始化最小值堆
min_heap = []
# 将所有数字添加到最小堆
for num in nums:
heapq.heappush(min_heap, -num)
# 提取并保存最大的两个数
if len(min_heap) >= 2:
max_num1 = -heapq.heappop(min_heap)
max_num2 = -heapq.heappop(min_heap)
else:
max_num1 = -min_heap[0] if len(min_heap) == 1 else None
max_num2 = None
# 将剩余的数字重新加回最小堆
while min_heap:
heapq.heappush(min_heap, -heapq.heappop(min_heap))
# 再次提取最大的两个数
if len(min_heap) >= 2:
second_max_num = -heapq.heappop(min_heap)
second_max_num2 = -heapq.heappop(min_heap)
else:
second_max_num = -min_heap[0] if len(min_heap) == 1 else None
second_max_num2 = None
return max_num1, max_num2, second_max_num, second_max_num2
# 测试
nums = [1, 2, 3, 4, 5]
max1, max2, sec_max1, sec_max2 = max_two(nums)
print("最大和次大的两个不同的元素分别是:", max1, max2, "和", sec_max1, sec_max2)
阅读全文