Leetcode - 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 = [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].
[分析] 首先要正确理解题意,结果是返回每个长度为k的窗口中的最大值。当窗口滑动一格时如何确定窗口中的最大值呢?直接的方法是遍历,则复杂度是O(k * n),选用最大堆存储窗口,则找到当前堆中最大值时O(1),窗口滑动时,需要添加一个新元素并删除窗口左边界元素,耗费为O(logk),因此总的复杂度是O(n*logk),当k很大时效率提升比较明显

public class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums == null)
            return null;
        if (nums.length == 0)
            return new int[0];
        int n = nums.length;
        int[] result = new int[n - k + 1];
        PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(k, new LargerComparator());
        for (int i = 0; i < k; i++) {
            maxHeap.offer(nums[i]);
        }
        result[0] = maxHeap.peek();
        int start = 0;
        for (int i = k; i < n; i++) {
            maxHeap.offer(nums[i]);
            maxHeap.remove(nums[start++]);
            result[i - k + 1] = maxHeap.peek();
        }
        return result;
    }
}
class LargerComparator implements Comparator<Integer> {
    public int compare(Integer o1, Integer o2) {
        return o2 - o1;
    }
}

你可能感兴趣的:(LeetCode)