队列思想及堆排序思想,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
前面哈希思想与链表复习
相关文章推荐
- 编程集训第3天:队列及堆排序思想--LeetCode滑动窗口的最大值(239)
- leetcode 239. Sliding Window Maximum 双端队列 滑动窗口最大值
- leetcode 239. Sliding Window Maximum 滑动窗口最大值Maximum + 优先级队列 + multiset + Heap
- Leetcode 239. 滑动窗口最大值
- Python实现最大优先队列
- LeetCode53. Maximum Subarray-python(easy) DP思想
- 单调队列的学习 - 滑动窗口求最大/小值
- Python :滑动窗口的最大值
- LeetCode--Maximum Depth of Binary Tree (检索二叉树的最大深度)Python
- leetcode_[python/C++] 179. Largest Number(数字组合成最大数)
- leetcode | 最大装水量问题 | python
- leetcode的python实现 刷题笔记53:最大子序和(多种解法)
- leetcode_107. Binary Tree Level Order Traversal II 二叉树层次遍历,利用python的list特性实现队列功能
- Leetcode 053 最大子序和 python 分治+动态规划
- 算法设计之,堆,堆排序,基于最大堆的最大优先队列的实现(C++实现)
- python剑指offer系列滑动窗口的最大值
- LeetCode 53 最大自序和 Python
- [151225] Python3 实现最大堆、堆排序,解决TopK问题
- LeetCode--Best Time to Buy and Sell Stock(最大利润)Python
- [Leetcode] Sliding Window Maximum 滑动窗口最大值