Sliding Window Maximum

[b]Sliding Window Maximum[/b]
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
return [3,3,5,5,6,7]

题目的意思是给定一个数组,一个长度为k的滑动窗口,从数组的最左边滑动到最右边,每次移动一个位置,找出每次窗口中最大的元素。这道题我们可以通过维护一个最大值的下标maxIndex,和一个最大值max来解决。遍历数组,每当窗口滑动后,我们通过最大值的下标来判断最大值元素是否还在窗口中,如果在,就只比较最大值和当前值就可以,做相应的处理;如果最大值元素不在窗口中,那我们就从这个窗口中找出最大值,时间复杂为O(k),这样总的时间复杂度为O(nk)。代码如下:

public class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums == null || nums.length == 0) return new int[0];
if(k == 1) return nums;
int maxIndex = 0;
int max = Integer.MIN_VALUE;
int index = 0;
int[] result = new int[nums.length - k + 1];

for(int i = 0; i < nums.length - k + 1; i++) {
if(i == 0 || maxIndex == i - 1) {
max = Integer.MIN_VALUE;
for(int j = i; j < i + k; j++) {
if(nums[j] > max) {
max = nums[j];
maxIndex = j;
}
}
} else {
if(nums[i + k - 1] > max) {
max = nums[i + k - 1];
maxIndex = i + k - 1;
}
}
result[index ++] = max;
}
return result;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值