您的位置:首页 > 编程语言 > Python开发

队列思想及堆排序思想,leetcode239. 滑动窗口最大值python

2018-12-20 21:02 996 查看

队列见数据结构之队列定义及基本操作实现

队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。队列中没有元素时,称为空队列。
队列的数据元素又称为队列元素。在队列中插入一个队列元素称为入队,从队列中删除一个队列元素称为出队。因为队列只允许在一端插入,在另一端删除,所以只有最早进入队列的元素才能最先从队列中删除,故队列又称为先进先出(FIFO—first in first out)线性表。

堆排序见图解排序算法(三)之堆排序

堆排序(英语:Heapsort)是指利用堆这种数据结构所设计的一种排序算法。堆是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。

leetcode239. 滑动窗口最大值python

题目

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:

Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
1 [3  -1  -3] 5  3  6  7       3
1  3 [-1  -3  5] 3  6  7       5
1  3  -1 [-3  5  3] 6  7       5
1  3  -1  -3 [5  3  6] 7       6
1  3  -1  -3  5 [3  6  7]      7

思路

下面代码有问题,待修改
使用了一个数组maxindex,存放着当前窗口的最大值和按需排列好的次大值的下标,并且这些次大值在数组中的位置只能是位于最大之后的,数组的最大规模为 k -1。

class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
maxindex= [0]     # 存放最大值,次大值下标的数组
res = []
for i in range(len(nums)):
if i -maxindex[0] > k-1:     # 判断下标对应的最大元素是否已经滑出窗口
maxindex.pop(0)
# nums[i]与 maxindex 中的值比较,将小于nums[i]的值都弹出
while (len(maxindex)>0 and nums[i] >= nums[maxindex[-1]]):
maxindex.pop()
if len(maxindex)< k-1:              # 如果maxindex的长度还没有达到最大规模
maxindex.append(i)
if i >=k-1:     # 如果经过一个完整的窗口,保存当前的最大值
res.append(nums[maxindex[0]])   #此行报错
return res

前面哈希思想与链表复习

哈希思想
链表

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: