Created
May 13, 2013 08:27
-
-
Save bittib/5566920 to your computer and use it in GitHub Desktop.
find max of K size sliding window from a stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Time Complexity: O(n) | |
*/ | |
public int[] minOfSlidingWindow(int[] A, int k){ | |
int n = A.length; | |
int[] B = new int[n - k + 1]; | |
int[] queue = new int[n]; | |
int head = 0, tail = 0; | |
for (int i=0; i<n; i++){ | |
while (head < tail && A[i] <= A[queue[tail-1]]) | |
tail--; | |
queue[tail++] = i; | |
if (i >= k-1){ | |
while (head < tail && i - queue[head] >= k) | |
head++; | |
B[i-k+1] = A[queue[head]]; | |
} | |
} | |
return B; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment