15 lines Java O(n) solution


  • 3
    public int[] maxSlidingWindow(int[] nums, int k) {
        if(nums.length == 0 || k > nums.length)
            return new int[0];
        LinkedList<Integer> win = new LinkedList<Integer>();
        int i = 0;
        int[] res = new int[nums.length - k + 1];
        while(i < nums.length){
            if(win.size() > 0 && win.peekLast() - win.peekFirst() + 1 == k)
                win.pollFirst();
    
            while(win.size() != 0 &&  nums[i] > nums[win.peekLast()])
                win.pollLast();
            
            win.offerLast(i);
            if(i>= k-1)
                res[i-k+1] = nums[win.peekFirst()];
            i++;
        }
        return res;
    }
    

    In order to do this in one round, the trick is keep the max of the win alway at the very front,


  • -1
    P

    Even though we are doing this in one pass..
    Worst case runtime solution is O(nk)


Log in to reply
 

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