• [leetcode-644-Maximum Average Subarray II]


    Given an array consisting of n integers, find the contiguous subarray whose length is greater than or equal to 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:
    when length is 5, maximum average value is 10.8,
    when length is 6, maximum average value is 9.16667.
    Thus return 12.75.
    

    Note:

    1. 1 <= k <= n <= 10,000.
    2. Elements of the given array will be in range [-10,000, 10,000].
    3. The answer with the calculation error less than 10-5 will be accepted

    思路:

    用一个sum去记录从开始到当前元素之前的所有元素的和,即sum[i]记录下标从0到i-1的所有元素的和。

    这样区间[i,j]的和就可以表示为sum[j+1] - sum[i].

    还发现 两句话效率不一样,上一句会超时。。。

     ret = max(ret,(sum[i+window]-sum[i])/window);//超时。。。
                    if (ret*window < (sum[i + window] - sum[i]))ret = (sum[i + window] - sum[i])/window;
    double findMaxAverage1(vector<int>& nums, int k)
        {
            int n = nums.size();
            vector<double>sum(n + 1,0);
            for (int i = 0; i < n; i++)sum[i + 1] = sum[i] + nums[i];
            double ret = -1e4;
            for (int i = 0; i <= n - k;i++)
            {
                for (int window = k; window + i <= n;window++)
                {
                    //ret = max(ret,(sum[i+window]-sum[i])/window);//超时。。。
                    if (ret*window < (sum[i + window] - sum[i]))ret = (sum[i + window] - sum[i])/window;
                }
            }
            return ret;
        }

    这种方法效率不是很高,看到有用二分查找思路的,还不是很懂,待优化。

  • 相关阅读:
    CSS背景background、backgroundposition使用详解
    为何img、input等内联元素可以设置宽、高
    各种Js封装
    CSS布局奇淫技巧之各种居中
    document.compatMode属性
    jquery的each()详细介绍
    jQuery所支持的css样式
    js,jQuery获取html5的data*属性
    PHP中MVC的编程思想浅谈
    php读取xml的神器
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/7190382.html
Copyright © 2020-2023  润新知