Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- class MonotonicQueue {
- Deque<Integer> queue;
- public MonotonicQueue() {
- queue = new ArrayDeque<>();
- }
- public void push(int a) {
- while(!queue.isEmpty() && queue.peekLast() < a) {
- queue.pollLast();
- }
- queue.offerLast(a);
- }
- public void pop(int a) {
- if(a == queue.peekFirst()) queue.pollFirst();
- }
- public int max() {
- return queue.peekFirst();
- }
- }
- public int[] maxSlidingWindow(int[] nums, int k) {
- int[] result = new int[nums.length - k + 1];
- MonotonicQueue mq = new MonotonicQueue();
- for(int i = 0; i < nums.length; i++) {
- mq.push(nums[i]);
- if(i >= k - 1) {
- result[i - k + 1] = mq.max();
- mq.pop(nums[i-k+1]);
- }
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement