滑动窗口的最大值

此博客链接:https://www.cnblogs.com/ping2yingshi/p/14437825.html

滑动窗口的最大值

题目链接:https://leetcode-cn.com/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof/

题目

给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。

示例:

输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
解释:

滑动窗口的位置 最大值
--------------- -----
[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
 

提示:

你可以假设 k 总是有效的,在输入数组不为空的情况下,1 ≤ k ≤ 输入数组的大小。

注意:本题与主站 239 题相同:https://leetcode-cn.com/problems/sliding-window-maximum/

题解

 先在每个滑动窗口中找到最大值,然后移动窗口,再次找最大值。这里先找出来第一个窗口中的最大值,当移动窗口找窗口中的额最大值时,先判断前一次移出滑动窗口的值是否为最大值,如果为最大值则重新遍历滑动窗口内的元素找最大值,如果移出的不是最大值,则把最大值和刚加入滑动窗口中的元素做比较取大值。

代码

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
   
       if(nums.length==0)
       {
        //    int ans[]=new int [1];
        //    ans[0]=nums[];
           return nums;
       }
         
        
       int max=nums[0];
       int res[]=new int[nums.length-k+1];
       for(int i=0;i<k;i++) 
       {
          max=Math.max(max,nums[i]); 
       }
       res[0]=max;
       var m=1;
       for(int i=1;i<=nums.length-k;i++)
       {
           if(nums[i-1]==max)  
             {
                 max=nums[i];
                for(int j=i;j<i+k;j++)
                {
                   max=Math.max(max,nums[j]);
                }
             }
             else{
                 max=Math.max(max,nums[i+k-1]);
             }
            res[m++]=max;
       }
       return res;
    }
}

结果

出来混总是要还的
原文地址:https://www.cnblogs.com/ping2yingshi/p/14437825.html