Simple Java Solution using PriorityQueue


  • 1
    R
    public class Solution {
        public int[] maxSlidingWindow(int[] nums, int k) {
            if(nums.length==0){
                return new int[0];
            }
            int i = 0;
            int count = 0;
            PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k, new Comparator<Integer>(){
                public int compare(Integer n1, Integer n2){
                    return n2 - n1;     
                }
                
            });
            int[] result = new int[nums.length - k + 1];
            for(i=0; i < k; i++){
                    
                    pq.add(nums[i]);
                    
                }
                i--;
            
            while(i<nums.length){
                i++;
                result[count] = pq.peek();
                count++;
                pq.remove(nums[i-k]);
                if(i<nums.length){
                    pq.add(nums[i]);
                }
            }
            return result;
        }
    }
    '''

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.