LeetCode 643. Maximum Average Subarray I 滑动窗口

题目要求如下

Given an array consisting of n integers, find the contiguous subarray
of given length k that has the maximum average value. And you need to
output the maximum average value.

Example 1:
Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75

Explanation:
Maximum average is (12-5-6+50)/4 = 51/4 = 12.75

Note: 1 <= k <= n <= 30,000.
Elements of the given array will be in the range [-10,000, 10,000].

如果直接计算这一题,例如k=4会想到4个4个求和找最大的那个。这就是滑动窗口的基本思想,不断取四个数,找出最大值。解法如下

class Solution {
    public double findMaxAverage(int[] nums, int k) {
      long sum=0;
        for(int i=0;i<k;i++)
            sum+=nums[i];
        long max=sum;
        for(int i=k;i<nums.length;i++){
            sum+=nums[i]-nums[i-k];
            max=Math.max(max,sum);
        }
        return (double)max/k;
    }
}

剑指offer中也有一道关于滑动窗口的题目,描述如下

给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5};针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1},{2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1},2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。

找出每个滑动窗口的最大值并输出,每个滑动窗口的最大值是有联系的,可以使用用一个双端队列,队列第一个位置保存当前窗口的最大值,当窗口滑动一次1.判断当前最大值是否过期
2.新增加的值从队尾开始比较,把所有比他小的值丢掉

解法如下

import java.util.*;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
        ArrayList<Integer> res = new ArrayList<>();
        if(size==0) return res;
        int begin;
        ArrayDeque<Integer> q = new ArrayDeque<>();
        for(int i=0;i<num.length;i++){
             begin = i - size + 1;//保存当前窗口的第一个值在原始数组中的下标
            if(q.isEmpty())
                 q.add(i);//存储下标
            else if(begin > q.peekFirst())//是否将最大值滑出
                q.pollFirst();
             while((!q.isEmpty()) && num[q.peekLast()] <= num[i])
                 q.pollLast();
            q.add(i);  
            if(begin >= 0)
                res.add(num[q.peekFirst()]);
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/srping123/article/details/77477750