版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83584221
题目:
Given an array consisting of
n
integers, find the contiguous subarray of given lengthk
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 <= k <= n <= 30,000
.
Elements of the given array will be in the range[-10,000,10,000]
.
解释:
找到数组nums
中均值长度为k
的均值最大的subarray的均值,需要注意的是,subsrray是连续的数组。
不用每次都计算和,首先求出最开始k
个数字的和,然后每次只要加上后一个数,再加上后一个数就是新的和了。
python代码:
class Solution(object):
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
last_sum=sum(nums[0:k])
max_sum=last_sum
for i in xrange(len(nums)-k):
last_sum=last_sum+nums[i+k]-nums[i]
max_sum=max(max_sum,last_sum)
return max_sum/float(k)
c++代码:
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
double last_sum=accumulate(nums.begin(),nums.begin()+k,0);
double max_sum=last_sum;
for (int i=0;i<nums.size()-k;i++)
{
last_sum+=nums[i+k]-nums[i];
max_sum=max(max_sum,last_sum);
}
return max_sum/k;
}
};
总结:
c++刚开始用int
结果最后小数点后几位精度不对,改成double以后就好了。