maxSlidingWindow-the maximum value of the sliding window

Subject requirements

Given an integer array nums, a sliding window of size k moves from the leftmost side of the array to the rightmost side of the array. You can only see the k numbers in the sliding window. The sliding window only moves one position to the right at a time.

Returns the maximum value in the sliding window.

Example 1:

Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
The maximum position of the sliding window


[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

Example 2:

Input: nums = [1], k = 1
Output: [1]

Example 3:

Input: nums = [1,-1], k = 1
Output: [1,-1]

Example 4:

Input: nums = [9,11], k = 2
Output: [11]

Example 5:

Input: nums = [4,-2], k = 2
Output: [4]

prompt:

1 <= nums.length <= 105
-104 <= nums[i] <= 104
1 <= k <= nums.length

Problem-solving ideas

1. First determine the number of return values
2. Find the maximum
value of the first k numbers 3.1 If the maximum value is the first number, push the window to the next number and find the maximum value again
3.2 If the maximum value is not the first If you push the window to the next number, you only need to judge which is greater than the largest number and the next number.
4Return the result
ps (maximum value search if there are multiple maximum values ​​for k numbers, the last position is the maximum value, reduce the amount of calculation afterwards)

Problem-solving code

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        int[] res=new int[nums.length-(k-1)];//用来存放结果
        int[] max1 = findMax(nums, 0, k);//找出最大值,和最大值的位置
        int max= max1[0];//最大值存入max变量中
        res[0]=max;//结果数组第一个值确定下来
         int flag =k;
         while (flag <nums.length)循环之后变量,找出每一回推的最大值
         {
             if(max1[1]==flag-k)//如果最大值是第一个值,则重新找最大值
             {
                 max1=findMax(nums,flag-k+1,k);
                 max=max1[0];
                 res[flag -k+1]=max;
             }
            else if(nums[flag]>=max)
            {
                res[flag -k+1]=nums[flag];
                max=nums[flag];
            }
            else
             {
                 res[flag -k+1]=max;
             }

             flag++;
         }
         return  res;
    }
    public int[] findMax(int[] nums,int s,int k)
    {
        int r =-1;//用来判断是否是第一个数
        int maxElem=Integer.MIN_VALUE;//找出最大值
        for (int i = s; i < s+ k; i++) {
            if(maxElem<=nums[i])
            {
                maxElem=nums[i];
                r =i;
            }

        }
        return new int[]{maxElem, r};
    }
}

effect

The info
answer was successful:
execution time: 773 ms, defeating 5.06% of Java users
Memory consumption: 59.3 MB, defeating 8.71% of Java users

Guess you like

Origin blog.csdn.net/tangshuai96/article/details/112104706