1.题目
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.
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].
翻译:给定一个包含n个整数的序列,找到给定长度k个连续的子序列,使得该序列有最大的平均值。你需要输出最大的平均值。
2.思路
莫名其妙错误的思路:两层循环,外层循环 i 从0到len-k,内层循环 j 每次从 i 到 i+k。输出是0,又看不到完全的测试用例,加个输出语句就超时。心态崩溃。
AC思路:类似滑动窗口,只使用一层循环。首先记录最开始的k个数组的和,之后将k长度的窗口右移,即用当前的和减去窗口左边的数,在加上窗口里的最后一个数。挑出最大的一个和,再除以k,求得最大平均值。
3.算法
class Solution { public double findMaxAverage(int[] nums, int k) { int len=nums.length; // long max=k*Integer.MIN_VALUE; // long temp=0; // double res=0; // for(int i=0;i<=len-k;i++){ // temp=0; // for(int j=i;j<=i+k-1;j++){ // temp+=nums[j]; // } // max=max>temp?max:temp; // } // System.out.println("max "+max); // res=(double)max/k; // return res; long otherSub=0; double res=0; long max=0; for(int i=0;i<k;i++){ otherSub+=nums[i]; } max=otherSub; for(int i=1;i<=len-k;i++){ otherSub=otherSub-nums[i-1]+nums[i+k-1]; max=max>otherSub?max:otherSub; } res=(double)max/k; return res; } }
4.总结
心很塞的就是第一种方法,不知道错在哪里。有大神能指点一下,就非常感谢了。