---
title: "Sliding Window Maximum"
author: "KickCode"
date: "2015-12-25T05:15:21Z"
tags: []
categories: ["编程语言"]
slug: "sliding-window-maximum"
draft: false
lastmod: "2015-12-25T05:15:21Z"
id: 2266370
url: "https://kickcode.iteye.com/blog/2266370"
---

**Sliding Window Maximum**
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 = , and k = 3.

Window position                Max
---------------               -----
 -3  5  3  6  7       3
 1  5  3  6  7       3
 1  3  3  6  7       5
 1  3  -1  6  7       5
 1  3  -1  -3  7       6
 1  3  -1  -3  5       7
return 

题目的意思是给定一个数组，一个长度为k的滑动窗口，从数组的最左边滑动到最右边，每次移动一个位置，找出每次窗口中最大的元素。这道题我们可以通过维护一个最大值的下标maxIndex，和一个最大值max来解决。遍历数组，每当窗口滑动后，我们通过最大值的下标来判断最大值元素是否还在窗口中，如果在，就只比较最大值和当前值就可以，做相应的处理；如果最大值元素不在窗口中，那我们就从这个窗口中找出最大值，时间复杂为O(k)，这样总的时间复杂度为O(nk)。代码如下：

```java

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;
    }
}

```