• [LeetCode] 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].

    给定一个由n个整数组成的数组,计算数组中相邻连续k个元素的最大平均值。按照题意使用了两层for循环计算结果,但是提交时显示超时。

    class Solution {
    public:
        double findMaxAverage(vector<int>& nums, int k) {
            double res = -INT_MAX;
            for (int i = 0; i != nums.size() - k + 1; i++) {
                double sum = 0;
                for (int j = i; j != i + k; j++) 
                    sum += nums[j];
                res = max(res, sum);
            }
            
            return res / k;
        }
    };
    // TLE
    TLE Code

    分析原因得到2层for循环导致超时,经过思考采用一个for循环来进行计算,每次计算到k的整数和时判断该和是否为最大值,接着把最k个数中第一个减去,再在后面添加一个整数。类似于滑动一个长度为k的窗口,代码如下

    class Solution {
    public:
        double findMaxAverage(vector<int>& nums, int k) {
            double res = INT_MIN;
            double sum = 0;
            for (int i = 0; i != nums.size(); i++) {
                sum += nums[i];
                if (i >= k)
                    sum -= nums[i - k];
                if (i >= k - 1)
                    res = max(res, sum);
            }
            return res / k;
        }
    };
    // 206 ms
  • 相关阅读:
    linux编译C
    Windows下ARP协议的工作原理简介
    窥探QQ基础数据库架构演变史
    JAVA培训—线程同步--卖票问题
    SQLite、MySQL和PostgreSQL 三种关系数据库哪个好?
    再论谭浩强《C语言程序设计》
    JPG加入RAR文件原理详解
    如何区分一个程序员是“老手“还是“新手“?
    AutoITx3.DLL所有函数及说明
    windows索引服务
  • 原文地址:https://www.cnblogs.com/immjc/p/7190361.html
Copyright © 2020-2023  润新知