Clean Java solution just using two arrays


  • 0
    C
    public class Solution {
        public int[] maxSlidingWindow(int[] nums, int k) {
            if(nums.length == 0 || k < 2 || nums.length < k) return nums;
            int len = nums.length + 1 - k;
            int[] window = new int[k];
            int[] result = new int[len];
            for(int i = 0; i < k; i++){
                window[i] = nums[i];
            }
            result[0] = maxValue(window);
            for(int i = 1; i < len; i++){
                window[(i-1)%k] = nums[i-1+k];
                //if the next int is the max, result[i] = the next int.
                if(nums[i-1+k] >= result[i-1]){
                    result[i] = nums[i-1+k];
                }else{
                    result[i] = maxValue(window);
                }
            }
            return result;
        }
        public int maxValue(int[] window){
            int max = window[0];
            for(int value : window){
                max = value>max? value: max;
            }
            return max;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.