zoukankan      html  css  js  c++  java
  • 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. 1 <= k <= n <= 30,000.
    2. Elements of the given array will be in the range [-10,000, 10,000].

     

    要完成的函数:

    double findMaxAverage(vector<int>& nums, int k)

     

    说明:

    这道题目十分容易,给定一个vector和数值k,我们可以得到长度为k的多个连续的子vector,要求返回这些子vector中的最大平均值。

    我们可以遍历一遍vector就得到了结果,存储和的最大值,最后除以k即可得到。

    为了降低花费的时间,我们也不需要每次都计算k个元素的和,减去最前面一个和加上新增加的一个即可,类似于滑动窗口。

    代码如下:

        double findMaxAverage(vector<int>& nums, int k) 
        {
            int s1=nums.size();
            int sum=0;
            for(int i=0;i<k;i++)
                sum+=nums[i];
            int i=1,max1=sum;
            while(i+k<=s1)
            {
                sum-=nums[i-1];
                sum+=nums[i+k-1];
                max1=max(max1,sum);
                i++;
            }
            return double(max1)/k;
        }

    上述代码实测174ms,beats 81.87% of cpp submissions。

  • 相关阅读:
    hdu 1251(字典树)
    hdu 1556(树状数组)
    hdu 3275(线段树的延迟标记,我被坑了)
    TCL之容器
    Codeforces Round #587 (Div. 3) D. Swords
    struts2中多个文件同时上传
    ffmpeg的使用
    struts2中类型转换器
    struts中访问servlet API的方法
    struts2中多个逻辑action(方法)的动态调用
  • 原文地址:https://www.cnblogs.com/chenjx85/p/9022543.html
Copyright © 2011-2022 走看看