java 239.最大滑动窗口(#)。java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 239.最大滑动窗口(#)。java相关的知识,希望对你有一定的参考价值。

public int[] maxSlidingWindow(int[] a, int k) {		
		if (a == null || k <= 0) {
			return new int[0];
		}
		int n = a.length;
		int[] r = new int[n-k+1];
		int ri = 0;
		// store index
		Deque<Integer> q = new ArrayDeque<>();
		for (int i = 0; i < a.length; i++) {
			// remove numbers out of range k
			while (!q.isEmpty() && q.peek() < i - k + 1) {
				q.poll();
			}
			// remove smaller numbers in k range as they are useless
			while (!q.isEmpty() && a[q.peekLast()] < a[i]) {
				q.pollLast();
			}
			// q contains index... r contains content
			q.offer(i);
			if (i >= k - 1) {
				r[ri++] = a[q.peek()];
			}
		}
		return r;
	}
public class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums == null || nums.length == 0) return nums;
        
        int[] result = new int[nums.length - k + 1];
        int max = findMax(nums, 0, k - 1);
        result[0] = max;
        for (int  i = 1; i < nums.length - k + 1; i++) {
            int current = i + k - 1;
            int previous = i - 1;
            
            if (nums[current] >= max) {
                max = nums[current];
            } else {
                if (nums[previous] == max) max = findMax(nums, i, current);    
            }
            
            result[i] = max;
        }
        
        return result;
    }
    
    private int findMax(int[] nums, int start, int end) {
        int max = Integer.MIN_VALUE;
        
        for (int i = start; i <= end; i++) {
            if (nums[i] > max) max = nums[i];
        }
        
        return max;
    }
}
public class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums == null || nums.length < 1 || k <= 0) return new int[0];
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(new Comparator<Integer>(){
            public int compare (Integer a, Integer b) {
                return b - a;
            }
        });
        int n = nums.length;
        int[] res = new int[n - k + 1];
        for (int i = 0; i < k; i++) {
            maxHeap.offer(nums[i]);
        }
        res[0] = maxHeap.peek();
        for (int i = k; i < n; i++) {
            maxHeap.remove(nums[i - k]);
            maxHeap.offer(nums[i]);
            res[i - k + 1] = maxHeap.peek();
        }
        return res;
    }
}

以上是关于java 239.最大滑动窗口(#)。java的主要内容,如果未能解决你的问题,请参考以下文章

java 239.最大滑动窗口(#)。java

java 239.最大滑动窗口(#)。java

java 239.最大滑动窗口(#)。java

java 239.最大滑动窗口(#)。java

java刷题--239滑动窗口最大值

LeetCode 239. 滑动窗口最大值(最大值的重新利用,Java)