-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[239. Sliding Window Maximum][Time Limit Exceeded]committed by LeetCo…
…de Extension
- Loading branch information
1 parent
178718b
commit e3ad629
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
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
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; | ||
} | ||
} |