Number4 AC
一道简单题,记的流水帐
话不多说,一道easy难度的题
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. Description: *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]. * Mycode:
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
auto be = nums.begin(), en = nums.end();
double sum = 0;
int tmp0 = 0, tmp1 = 0;
for(int i = k; i != 0; --i, ++be){
tmp1 += *be;
}
sum = tmp1;
for(; be != en; ++be){
tmp0 = tmp1 - *(be - k) + *be;
if(tmp0 > sum){
sum = tmp0;
}
tmp1 = tmp0;
}
return sum/k;
}
};
全页截图:

以上
:stuck_out_tongue_closed_eyes:
Last modified on 2017-07-20