• 643. 子数组最大平均数 I(javascript)643. Maximum Average Subarray I


    给你一个由 n 个元素组成的整数数组 nums 和一个整数 k 。

    请你找出平均数最大且 长度为 k 的连续子数组,并输出该最大平均数。

    任何误差小于 10-5 的答案都将被视为正确答案。

    You are given an integer array nums consisting of n elements, and an integer k.

    Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted.

    示例 1:

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

    示例 2:

    输入:nums = [5], k = 1
    输出:5.00000
    
    • 1
    • 2

    提示:

    n == nums.length
    1 <= k <= n <= 105
    -104 <= nums[i] <= 104
    
    • 1
    • 2
    • 3

    Number.MIN_SAFE_INTEGER代表在 JavaScript中最小的安全的integer型数字

    解题思路:

    1. 先定义一个数,并赋值JavaScript中最小的安全的integer型数字
    2. 循环遍历数组范围(0~nums.length - k + 1)
    3. 在对长度为k的截取到的数组([i,i+k])进行遍历求和
    4. 再将长度为k的数组之和 和getMax 取最大值
    5. getMax / k为最终得到的值
    /**
     * @param {number[]} nums
     * @param {number} k
     * @return {number}
     */
    var findMaxAverage = function (nums, k) {
        let getMax = Number.MIN_SAFE_INTEGER;
        for (let i = 0; i < nums.length - k + 1; i++) {
            let number = 0
            for (let j = i; j < i + k; j++) {
                number += nums[j]
            }
            getMax = Math.max(getMax, number)
            number = 0
        }
        return getMax / k
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    /**
     * @param {number[]} nums
     * @param {number} k
     * @return {number}
     */
    var findMaxAverage = function (nums, k) {
        let sum = 0;
        for (let i = 0; i < k; i++) {
            sum += nums[i]// 获取第一个 k 长度的数组的总数当做参照物
        }
        let getMax = sum
        for (let i = k; i < nums.length; i++) {
            sum = sum - nums[i - k] + nums[i] //滑格子 减掉数组最前面一位 加数组后面一位
            getMax = Math.max(getMax, sum)//获取最大值
        }
        return getMax / k
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    leetcode:https://leetcode.cn/problems/maximum-average-subarray-i/submissions/

  • 相关阅读:
    Mybit-Plus
    【css】iconfont的使用
    (附源码)springboot在线考试系统 毕业设计 160935
    SpringBoot+Mybatis+Thymeleaf实现垃圾分类系统
    MotoSimEG-VRC软件:安川机器人用户坐标系介绍与标定方法
    oracle 简易客户端上使用rman
    元宇宙电商-NFG系统是如何赋能酒业的?
    执行上下文,js、React、HTML中的this
    R语言几何图像可视化
    C++多态(超级详细版)
  • 原文地址:https://blog.csdn.net/ingenuou_/article/details/126870521