-
Notifications
You must be signed in to change notification settings - Fork 34
/
Solution.java
38 lines (38 loc) · 1.16 KB
/
Solution.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
public class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums.length==0||k==0||k==1) {
return nums;
}
List<Integer> maxList=new ArrayList<Integer>();
for (int i = 0; i < k; i++) {
while (maxList.size()!=0) {
if (maxList.get(maxList.size()-1)<nums[i]) {
maxList.remove(maxList.size()-1);
}else {
break;
}
}
maxList.add(nums[i]);
}
int[] ans=new int[nums.length-k+1];
ans[0]=maxList.get(0);
for (int i = k; i < nums.length; i++) {
//排队出去一个
if (nums[i-k]==maxList.get(0)) {
maxList.remove(0);
}
//排队进来一个
while (maxList.size()!=0) {
if (maxList.get(maxList.size()-1)<nums[i]) {
maxList.remove(maxList.size()-1);
}else {
break;
}
}
maxList.add(nums[i]);
//赋值
ans[i-k+1]=maxList.get(0);
}
return ans;
}
}