Friday, October 6, 2017

Sliding Window Second Maximum

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. 

For example:
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3. 
Then, return the second max sliding window [1, -1, -1, 3, 5, 6] .

/* time: amortized O(n), space:O(n) */
import java.util.*;

public class Solution {
public static int[] test(int[] nums, int k) {
if (nums == null || nums.length <= 1 || k <= 1) {
return nums;
}
if (k > nums.length) {
k = nums.length;
}
int[] res = new int[nums.length - k + 1];
Deque<Integer> deque = new ArrayDeque<>();
int maxNumIndex = 0;
int index = 0;
for (int i = 1; i < nums.length; i++) {
if (!deque.isEmpty() && deque.peek() < i - k + 1) {
deque.poll();
}
if (maxNumIndex < i - k + 1) {
maxNumIndex = deque.poll();
}
if (nums[i] > nums[maxNumIndex]) {
int temp = maxNumIndex;
maxNumIndex = i;
while (!deque.isEmpty() && temp > deque.peek()) {
deque.poll();
}
deque.offerFirst(temp);
} else {
while (!deque.isEmpty() && nums[i] > nums[deque.peekLast()]) {
deque.pollLast();
}
deque.offer(i);
}
if (i >= k - 1) {
res[index++] = nums[deque.peek()];
}
}
return res;
}
public static void main(String[] args) {
int[] nums = {1, 3, -1, -3, 5, 3, 6, 7};
int[] t0 = test(nums, 1);
int[] t1 = test(nums, 2);
int[] t2 = test(nums, 3);
int[] t3 = test(nums, 4);
int[] t4 = test(nums, 5);
int[] t5 = test(nums, 6);
int[] t6 = test(nums, 7);
int[] t7 = test(nums, 8);
int[] t8 = test(nums, 9);
int[] t9 = test(nums, 10);
System.out.println(Arrays.toString(t0));
System.out.println(Arrays.toString(t1));
System.out.println(Arrays.toString(t2));
System.out.println(Arrays.toString(t3));
System.out.println(Arrays.toString(t4));
System.out.println(Arrays.toString(t5));
System.out.println(Arrays.toString(t6));
System.out.println(Arrays.toString(t7));
System.out.println(Arrays.toString(t8));
System.out.println(Arrays.toString(t9));
}
}

No comments:

Post a Comment