队列、堆排序与LeetCode 239

一、队列

队列是受限的线性表,对元素来讲一般是先进先出。但是双端队列在首尾都有指针,可以实现更多的方便功能。

二、堆排序

堆排序分成最大堆和最小堆,即以最大值作为根节点或者以最小值作为根节点,但是对于排序来讲,他们的过程相同。

  • 首先是将所有元素按顺序组成一颗树。
  • 然后从叶子结点到父节点到根节点依次排序,按照大小交换顺序,最终即成有序堆。

三、LeetCode 239

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.

Example:

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
  • 思路:用长度为k的双端队列存储,最大值总是存在队列头,较小值存在队列后,保持整个队列是递减的,每次输出队列头即可。

  • 代码如下:

class Solution:
    def maxSlidingWindow(self, nums, k):
        res = []
        q = []
        for i in range(len(nums)):
            # q[0] 过期,丢弃
            while q and q[0] <= i - k: 
                q.pop(0)
            # q[-1] 较小,丢弃
            while q and nums[q[-1]] <= nums[i]: 
                q.pop(-1)
            q.append(i)
            if i < k-1: # 凑齐k个数才输出
                continue
            res.append(nums[q[0]])
        return res

结果如下:

四、哈希表与链表回顾

  • 哈希表 主要是一种以空间换时间的数据结构,追求效率,查找和插入的时间复杂度都为O(1)。
  • 链表 主要是在插入的时候可以达到O(1)的复杂度,但是在查找特定编号节点需要O(n)的时间。
发布了89 篇原创文章 · 获赞 37 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/u012891055/article/details/85141555