zoukankan      html  css  js  c++  java
  • [Leetcode]643.Maximum Average Subarray I

    链接:LeetCode643

    给定(n)个整数,找出平均数最大且长度为$ k $的连续子数组,并输出该最大平均数。

    示例 1:

    输入: ([1,12,-5,-6,50,3]), k = 4
    输出: 12.75
    解释: 最大平均数 (12-5-6+50)/4 = 51/4 = 12.75

    相关标签:滑动窗口

    重点在于构造滑动窗口,以(k)为窗口大小往后滑动,注意判空即可。代码如下:

    python:

    class Solution:
        def findMaxAverage(self, nums: List[int], k: int) -> float:
            if not nums:
                return 0
            cur = res = sum(nums[:k])
            start = 0
            for end in range(k,len(nums)):
                cur += -nums[start]+nums[end]
                start += 1
                res = max(cur,res)
            return res/k
    

    C++:

    class Solution {
    public:
        double findMaxAverage(vector<int>& nums, int k) {
            if(nums.empty()){
                return 0;
            }
            double start,cur,res;
            start  = cur = res = 0;
            for(int i = 0;i<k;i++){
                cur += nums[i];
            }
            res = cur;
            for(int i=k;i<nums.size();i++){
                cur += nums[i]-nums[start];
                start += 1;
                res = max(res,cur);
            }
            return res/k;
        }
    };
    
  • 相关阅读:
    [POI2014]KUR-Couriers
    MySQL有哪些索引
    索引的设计原则
    explain参数之extra
    explain参数之type
    explain参数之select_type
    如何查询最后一行的记录
    为什么MySQL自增id不连续?
    MySQL字符集
    MySQL有哪些优化策略?
  • 原文地址:https://www.cnblogs.com/hellojamest/p/12210456.html
Copyright © 2011-2022 走看看