Java O(n) using simple and basic comparing, beating 98% submissions.


  • 0
    Z

    public int[] maxSlidingWindow(int[] nums, int k) {

        if(k == 1 || nums.length == 0){
            return nums;
        }
        int[] res = new int[nums.length - k + 1];
        int max = -1;
        for(int i = 0 ; i < k; i++){
            if(nums[i] > max) 
            max = nums[i];
        }
        res[0] = max;      
        for(int i = 1; i < res.length; i++){
            if(nums[i + k - 1] > max){
            res[i] = nums[i + k - 1];
            max = res[i];
            }else if(nums[i + k - 1] == max){
              res[i] = max; 
            }else{
                if(max != nums[i - 1] )
                    res[i] = max;
                else{
                    max = nums[i];
                    for(int j = 0; j < k; j ++){
                        if(max < nums[j + i])
                        max = nums[j + i];
                    }
                    res[i] = max;
                }                
            }
        }
        return res;
    

    }
    '''


Log in to reply
 

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