zoukankan      html  css  js  c++  java
  • LeetCode239 滑动窗口最大值

    class Solution {
        public int[] maxSlidingWindow(int[] nums, int k) {
            //双指针滑窗
            int l = nums.length;
             if( l == 0)return nums;
             int[] res = new int[l - k + 1];
             
             LinkedList<Integer> queue = new LinkedList<>();
             int index  = 0;
             for(int i = 0 ; i < l ; i++)
             {
                 while(!queue.isEmpty() && nums[queue.peekLast()] <= nums[i]){ //当前队列为空或者队尾元素比当前值要小
                     queue.pollLast(); //不断的把最后的元素压出
                 }
                 queue.addLast(i);//加入索引值
                 //考虑 l 和 r 的值
                 if(queue.peek() <= i - k ) //判断滑窗大小
                 {
                     queue.poll();
                 }
    
                 //
                 if( i + 1 >= k)
                 {
                    res[index] = nums[queue.peek()];
                    index++;
                 }
    
    
             }
             return res;
        }
        //使用大顶堆
        public int helper(int[] arr , int l , int k)
        {
             PriorityQueue<Integer> maxheap = new PriorityQueue<Integer>(new Comparator<Integer>() {
                @Override
                public int compare(Integer o1, Integer o2) {
                    return o2-o1;
                }
            }); // 实现大顶堆
            for(int i = l ; i < k ; i++)
            {
                maxheap.add(arr[i]);
            }
            return maxheap.poll();
           
        }
    }
  • 相关阅读:
    jQuery选择器之层级选择器
    信息滚动制作
    scrollTop、offsetTop、clientTop
    模电GG
    matlab求解线性方程组
    NWERC2016I
    WEB开发资料集散
    NWERC2016H
    相量变换的性质
    GCJ2017R1C B. Parenting Partnering
  • 原文地址:https://www.cnblogs.com/swqblog/p/12886190.html
Copyright © 2011-2022 走看看