Skip to content

Commit

Permalink
[239. Sliding Window Maximum][Time Limit Exceeded]committed by LeetCo…
Browse files Browse the repository at this point in the history
…de Extension
  • Loading branch information
seaskymonster committed Oct 1, 2016
1 parent 178718b commit e3ad629
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions 239-Sliding-Window-Maximum/solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
public class Solution {
public void addElement(Deque<Integer> dq, int element){
while(!dq.isEmpty() && dq.peekLast() <= element){
dq.pollLast();
}
dq.offerLast(element);
}

public void removeElement(Deque<Integer> dq, int element){
if(!dq.isEmpty() && dq.peekFirst() == element){
dq.pollFirst();
}
}
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null || k <= 0) {
return new int[0];
}

Deque<Integer> dq = new ArrayDeque<Integer>();
int length = nums.length;
int[] result = new int[length - k +1];
for(int i =0; i <k-1; i++){
addElement(dq, nums[i]);
}
for(int j = k-1; j < nums.length; j++){
addElement(dq, nums[j]);
result[j-k+1] = dq.peekFirst();
removeElement(dq, nums[j-k+1]);
}
return result;
}
}

0 comments on commit e3ad629

Please sign in to comment.