Java Solution 4ms- beats97.31%


  • 0

    I am using to compare two things, 1. The remove value is the maxTmp or not? 2. The new add value is greater than the maxTmp or not? And here is the code:

    class Solution {
        public int findMax(int[] nums, int i, int j) {
    		int maxTmp = nums[i];
                    for(int a = i; a <= j; a++) {
            		maxTmp = Math.max(maxTmp, nums[a]);
                    }
                    return maxTmp;
    	}
    	public int[] maxSlidingWindow(int[] nums, int k) {
                    if(k == 0){
                        return new int[]{};
                    }
                    if(nums.length == k){
                        return new int[]{findMax(nums, 0, k-1)};
                    }
                    int[] max = new int[nums.length-k+1];
                    int currMax = findMax(nums, 0, k-1);
                    max[0] = currMax;
                    for(int i = 1; i+k-1 < nums.length;i++) {
            		if(nums[i-1] == currMax) {
            			currMax = findMax(nums, i, i+k-1);
            		}
            		else if(nums[i+k-1] > currMax){
            			currMax = nums[i+k-1];
            		}
            		max[i] = currMax;
                    }
                    return max;
            }
    }
    

Log in to reply
 

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