当前位置:网站首页>LeetCode_643_子数组的最大平均数Ⅰ
LeetCode_643_子数组的最大平均数Ⅰ
2022-08-04 12:46:00 【Fitz1318】
题目链接
题目描述
给你一个由 n 个元素组成的整数数组 nums 和一个整数 k 。
请你找出平均数最大且 长度为 k 的连续子数组,并输出该最大平均数。
任何误差小于 1 0 − 5 10^{-5} 10−5 的答案都将被视为正确答案。
示例 1:
输入:nums = [1,12,-5,-6,50,3], k = 4
输出:12.75
解释:最大平均数 (12-5-6+50)/4 = 51/4 = 12.75
示例 2:
输入:nums = [5], k = 1
输出:5.00000
提示:
n == nums.length1 <= k <= n <= 10^5-10^4 <= nums[i] <= 10^4
解题思路
滑动窗口
滑动窗口,记录每k个数的和,总和最大的平均值也就最大
AC代码
class Solution {
public double findMaxAverage(int[] nums, int k) {
int left = 0;
int right = k;
int sum = 0;
for (left = 0; left < right; left++) {
sum += nums[left];
}
int maxSum = sum;
for (left = 0, right = k; right < nums.length; left++, right++) {
sum = sum - nums[left] + nums[right];
maxSum = Math.max(sum, maxSum);
}
return 1.0 * maxSum / k;
}
}
边栏推荐
猜你喜欢
随机推荐
业务中我们如何更新缓存?Redis
高手,云集在于REST、gRPC 和 GraphQL之间!
程序猿七夕礼物-如何30分钟给女朋友快速搭建专属语聊房
Motion Regulations (18) - and check the basic questions - gang
【UML】信息系统分析与设计知识点总结
Escape character is ‘^]’什么意思?怎么使用telnet
Django框架MySQL数据库到models模型的映射关系
Two years of independent development experience Programmers tell us the experience of making money (listen to the masters who really make money)
Opencv学习之ORB特征提取和匹配
干货丨数学规划视角下的分货优化解题思路
双目立体视觉笔记(三)三角测量、极线校正
划重点!2022面试必刷461道大厂架构面试真题汇总+面经+简历模板
《独行月球》猛药,治不了开心麻花内耗
Do you understand the various configurations in the project?
LeetCode Daily Question (858. Mirror Reflection)
Js获取当前页面url参数
使用SQLServer复制数据库
leetcode 48. Rotate Image 旋转图像(Medium)
Yolov5 test and train own dataset
HDU1580 输出先手能取的方案数









