|
| 1 | +import java.util.Arrays; |
| 2 | + |
| 3 | +/** |
| 4 | + * Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the |
| 5 | + * very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. |
| 6 | + * <p> |
| 7 | + * For example, |
| 8 | + * Given nums = [1,3,-1,-3,5,3,6,7], and k = 3. |
| 9 | + * <p> |
| 10 | + * Window position Max |
| 11 | + * --------------- ----- |
| 12 | + * [1 3 -1] -3 5 3 6 7 3 |
| 13 | + * 1 [3 -1 -3] 5 3 6 7 3 |
| 14 | + * 1 3 [-1 -3 5] 3 6 7 5 |
| 15 | + * 1 3 -1 [-3 5 3] 6 7 5 |
| 16 | + * 1 3 -1 -3 [5 3 6] 7 6 |
| 17 | + * 1 3 -1 -3 5 [3 6 7] 7 |
| 18 | + * Therefore, return the max sliding window as [3,3,5,5,6,7]. |
| 19 | + * <p> |
| 20 | + * Note: |
| 21 | + * You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array. |
| 22 | + * <p> |
| 23 | + * Follow up: |
| 24 | + * Could you solve it in linear time? |
| 25 | + * <p> |
| 26 | + * Created by drfish on 12/06/2017. |
| 27 | + */ |
| 28 | +public class _239SlidingWindowMaximum { |
| 29 | + public int[] maxSlidingWindow(int[] nums, int k) { |
| 30 | + if (nums == null || nums.length < 1) { |
| 31 | + return new int[0]; |
| 32 | + } |
| 33 | + int[] leftMax = new int[nums.length]; |
| 34 | + int[] rightMax = new int[nums.length]; |
| 35 | + leftMax[0] = nums[0]; |
| 36 | + rightMax[nums.length - 1] = nums[nums.length - 1]; |
| 37 | + for (int i = 1; i < nums.length; i++) { |
| 38 | + leftMax[i] = (i % k == 0) ? nums[i] : Math.max(leftMax[i - 1], nums[i]); |
| 39 | + int j = nums.length - i - 1; |
| 40 | + rightMax[j] = (j % k == 0) ? nums[j] : Math.max(rightMax[j + 1], nums[j]); |
| 41 | + } |
| 42 | + int[] result = new int[nums.length - k + 1]; |
| 43 | + for (int i = 0; i + k <= nums.length; i++) { |
| 44 | + result[i] = Math.max(leftMax[i + k - 1], rightMax[i]); |
| 45 | + } |
| 46 | + return result; |
| 47 | + } |
| 48 | + |
| 49 | + public static void main(String[] args) { |
| 50 | + _239SlidingWindowMaximum solution = new _239SlidingWindowMaximum(); |
| 51 | + assert Arrays.equals(new int[]{3, 3, 5, 5, 6, 7}, solution.maxSlidingWindow(new int[]{1, 3, -1, -3, 5, 3, 6, |
| 52 | + 7}, 3)); |
| 53 | + } |
| 54 | +} |
0 commit comments