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.總結
心很塞的就是第一種方法,不知道錯在哪裏。有大神能指點一下,就非常感謝了。