Java 9 lines 5 ms solution (beats 96%)


  • 0
        public int[] maxSlidingWindow(int[] a, int k) {
            if (a.length == 0 || k == 0) return new int[0];
            int max[] = new int[a.length - k + 1], q[] = new int[a.length], head = 0, tail = 0; 
            for (int i = 0; i < a.length; i++) {
                while (tail > head && q[head] < i - k + 1)   head++;
                while (tail > head && a[q[tail - 1]] < a[i]) tail--;
                q[tail++] = i;
                if (i >= k - 1) max[i - k + 1] = a[q[head]];
            }       
            return max;
        }
    

Log in to reply
 

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