Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

239. Sliding Window Maximum

You are given an array of integers 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.

Return the max sliding window.

Example 1:

1
2
3
4
5
6
7
8
9
10
11
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7

Example 2:

1
2
Input: nums = [1], k = 1
Output: [1]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
TC: O(n), SC: O(n)

public class Solution {
class MaxQueue {

Deque<Integer> maxs, nums;

MaxQueue() {
maxs = new LinkedList<>();
nums = new LinkedList<>();
}

void offer(int num) {
nums.offer(num); // add method throws an exception and offer doesn't.
while (!maxs.isEmpty() && maxs.peekLast() < num) {
maxs.pollLast();
}
maxs.offerLast(num);
}

Integer poll() {
Integer res = null;
if (!nums.isEmpty()) {
res = nums.poll();
if (res.equals(maxs.peekFirst())) {
maxs.pollFirst();
}
}

return res;
}

Integer getMax() {
Integer res = null;
if (!maxs.isEmpty()) {
res = maxs.peekFirst();
}

return res;
}
}
public int[] maxSlidingWindow(int[] nums, int k) {
int n = nums.length;
int[] res = new int[n-k+1];

if (n == 0 || k == 0) {
return new int[0];
}

MaxQueue mq = new MaxQueue();

for (int i = 0; i < k; i++) {
mq.offer(nums[i]);
}

res[0] = mq.getMax();

for (int i = k; i < n; i++) {
mq.poll();
mq.offer(nums[i]);
res[i-k+1] = mq.getMax();
}

return res;
}
}

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels