zoukankan      html  css  js  c++  java
  • leetcode刷题笔记 239题 滑动窗口最大值

    leetcode刷题笔记 239题 滑动窗口最大值

    源地址:239. 滑动窗口最大值

    问题描述:

    给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。

    返回滑动窗口中的最大值。

    进阶:

    你能在线性时间复杂度内解决此题吗?

    示例:

    输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
    输出: [3,3,5,5,6,7]
    解释:

    滑动窗口的位置 最大值


    [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

    提示:

    1 <= nums.length <= 10^5
    -10^4 <= nums[i] <= 10^4
    1 <= k <= nums.length

    /*
    本题使用单调队列的思路,即保证队列长度的前提下,构成从大到小的队列,这么每次进行新元素入队出队时,只需向res中插入队列的head元素
    
    scala中双端队列使用ArrayDeque数据结果,队首元素为head,队尾元素为last。出队使用removeHead和removeLast,入队使用append
    */
    import scala.collection.mutable
    object Solution {
        def maxSlidingWindow(nums: Array[Int], k: Int): Array[Int] = {
            var queue = new mutable.ArrayDeque[Int]()
            var res = Array[Int]()
            
            for (i <- 0 to nums.length-1) {
                if (queue.size > 0 && i - k + 1 > queue.head) queue.removeHead()
                while (queue.size > 0 && nums(i) >= nums(queue.last)) queue.removeLast()
                queue.append(i)
                if (i >= k - 1)  res = res.appended(nums(queue.head))
            }
            
            return res
        }
    }
    
  • 相关阅读:
    lLinux 下 Stress 压力测试工具
    zabbix 微信告警配置
    spark Intellij IDEA开发环境搭建
    Spark调优与调试
    在centos 6.5 x64中安装 spark-1.5.1
    二叉树的各种遍历算法
    ServletResponse的一些知识点
    UVA 10303 How Many Trees? (catlan)
    UVA 10183 How Many Fibs?
    UVA 10471 Gift Exchanging
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13890264.html
Copyright © 2011-2022 走看看