# Hard-题目15：239. Sliding Window Maximum

90人阅读 评论(0)

Given an array 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.

For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

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

Therefore, return the max sliding window as [3,3,5,5,6,7].

public class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums.length==0)
return new int[0];
int[] window = new int[nums.length-k+1];
int j=0;
for(int i = 0;i<nums.length;i++) {
while (!deque.isEmpty() && nums[deque.getLast()] < nums[i]) {
deque.removeLast();
}
if(deque.getFirst() == i-k)
deque.removeFirst();
if(i>=k-1)
window[j++] = nums[deque.getFirst()];
}
return window;
}
}

29ms,beats 62.07%,众数31ms,9.54%
Cmershen的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：55672次
• 积分：3195
• 等级：
• 排名：第10669名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论