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. Return the max sliding window.
Follow up:
Could you solve it in linear time?
Example:
Input: nums = [1,3,-1,-3,5,3,6,7]
, and k = 3
Output: [3,3,5,5,6,7]
Explanation:
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
思路:起码两个指针的暴力做法可以想一想。
public int[] maxSlidingWindow(int[] nums, int k) { if(nums == null || k <= 0) return new int [0]; int [] arr = new int[nums.length - k + 1]; for(int i = 0; i < nums.length - k + 1; i++){ int max = Integer.MIN_VALUE; for(int j = i; j < i + k; j++) max = Math.max(max, nums[j]); arr[i] = max; } return arr; }
coinbase oa
public int minSlidingWindow(List<Integer> nums, int k) { if(nums == null || k <= 0) return -1; int [] arr = new int[nums.size() - k + 1]; for(int i = 0; i < nums.size() - k + 1; i++){ int min = Integer.MAX_VALUE; for(int j = i; j < i + k; j++) min = Math.min(min, nums.get(j)); arr[i] = min; } int max = Integer.MIN_VALUE; for (int k = 0; k < arr.length; k++) { max = Math.max(max, arr[k]); } return max; }
能全过的代码
public static int segment(int w, List<Integer> in) { // Write your code here final int[] min_left = new int[in.size()]; final int[] min_right = new int[in.size()]; min_left[0] = in.get(0); min_right[in.size() - 1] = in.get(in.size() - 1); for (int i = 1; i < in.size(); i++) { min_left[i] = (i % w == 0) ? in.get(i) : Math.min(min_left[i - 1], in.get(i)); final int j = in.size() - i - 1; min_right[j] = (j % w == 0) ? in.get(j) : Math.min(min_right[j + 1], in.get(j)); } final int[] sliding_min = new int[in.size() - w + 1]; for (int i = 0, j = 0; i + w <= in.size(); i++) { sliding_min[j++] = Math.min(min_right[i], min_left[i + w - 1]); } int max = Integer.MIN_VALUE; for (int idx = 0; idx < sliding_min.length; idx++) { max = Math.max(max, sliding_min[idx]); } return max; } }