-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path0239.滑动窗口最大值.java
84 lines (80 loc) · 1.92 KB
/
0239.滑动窗口最大值.java
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.util.Deque;
import java.util.LinkedList;
/*
* @lc app=leetcode.cn id=239 lang=java
*
* [239] 滑动窗口最大值
*
* https://leetcode.cn/problems/sliding-window-maximum/description/
*
* algorithms
* Hard (49.95%)
* Likes: 1700
* Dislikes: 0
* Total Accepted: 311.8K
* Total Submissions: 624.2K
* Testcase Example: '[1,3,-1,-3,5,3,6,7]\n3'
*
* 给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k
* 个数字。滑动窗口每次只向右移动一位。
*
* 返回 滑动窗口中的最大值 。
*
*
*
* 示例 1:
*
*
* 输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
* 输出:[3,3,5,5,6,7]
* 解释:
* 滑动窗口的位置 最大值
* --------------- -----
* [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
*
*
* 示例 2:
*
*
* 输入:nums = [1], k = 1
* 输出:[1]
*
*
*
*
* 提示:
*
*
* 1 <= nums.length <= 10^5
* -10^4 <= nums[i] <= 10^4
* 1 <= k <= nums.length
*
*
*/
// @lc code=start
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int[] ans = new int[nums.length - k + 1];
Deque<Integer> queue = new LinkedList<>();
for (int r = 0; r < nums.length; r++) {
while (!queue.isEmpty() && nums[r] >= nums[queue.peekLast()]) {
queue.removeLast();
}
queue.addLast(r);
int l = r - k + 1;
if (queue.peekFirst() < l) {
queue.removeFirst();
}
if (r + 1 >= k) {
ans[l] = nums[queue.peekFirst()];
}
}
return ans;
}
}
// @lc code=end