• LeetCode 239


    原题:https://leetcode-cn.com/problems/sliding-window-maximum/

    给定一个数组 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

    这个题一开始我看错了,以为是求滑动窗口内的总和。。

    后来细看题目才知道是求k个窗口内的最大值,一开始也是没有思绪。后来看了标签才想起最大堆来维护当前窗口内的数值。

    具体也不多说了,很简单的一个思想。

    class Solution {
        public int[] maxSlidingWindow(int[] nums, int k) {
         PriorityQueue<Integer> dump = new PriorityQueue<>(3, new Comparator<Integer>() {
                @Override
                public int compare(Integer o1, Integer o2) {
                    return o2.compareTo(o1);
                }
            });
    
            ArrayList<Integer> list = new ArrayList<>();
            int currentBig = Integer.MIN_VALUE;
            int temp = 0;
            Queue<Integer> queue = new LinkedList<>();
            for(int i = 0; i <nums.length;i++){
                queue.add(nums[i]);
                dump.add(nums[i]);
                temp = nums[i];
                if(temp  > currentBig){
                    currentBig = temp;
                }
                if(queue.size() == k ){
                    list.add(currentBig);
                    dump.remove(queue.poll());
                    if(!dump.isEmpty()) {
                        currentBig = dump.peek();
                    }else {
                        currentBig = Integer.MIN_VALUE;
                    }
                }
            }
            if(k>nums.length){
                list.add(currentBig);
            }
            int[] result = new int[list.size()];
            int i = 0;
            for(int a:list){
                result[i++] = a;
            }
            return  result;
        }
    }

    做完题看了评论区的各位大佬的算法才知道自己是多么的垃圾啊!

  • 相关阅读:
    细说java平台日志组件
    linux远程执行命令
    linux命令 common 文件比较
    Linux Shell脚本编程--cut命令
    linux sort命令
    shell中if判断一个变量为空
    linux shell if参数
    wc命令
    date 命令
    let 与 expr Shell运算比较 let强强胜出
  • 原文地址:https://www.cnblogs.com/ZJPaang/p/12665529.html
Copyright © 2020-2023  润新知