JAVA solution with PriorityQueue


  • 0
    W
     public int[] maxSlidingWindow(int[] nums, int k) {
        
        if(nums.length== 0 || k== 0)
            return new int[0];
        
        int l= nums.length;
        int[] res= new int[l-k+ 1];
        PriorityQueue<Integer> pq= new PriorityQueue<Integer>(k, Collections.reverseOrder());
        
        for(int i= 0; i< k; i++){
            pq.add(nums[i]);
        }
    
        res[0]= pq.peek();
        
        for(int i= k; i< l; i++){
            pq.remove(nums[i-k]);
            pq.add(nums[i]);
            res[i- k + 1]= pq.peek();
        }
        
        return res;
        
    }

Log in to reply
 

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