643. Maximum Average Subarray I 最大子数组的平均值

[抄题]:

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

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

sliding window 最一般的步骤就是右加左减,直接写就行了

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

sliding window : 框的长度恒定

[关键模板化代码]:

for (int i = k; i < nums.length; i++) {
            sum = sum + nums[i] - nums[i - k];

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

644. Maximum Average Subarray II 长度可以更长。贼复杂的二分法,有点无聊。

 [代码风格] :

class Solution {
    public double findMaxAverage(int[] nums, int k) {
        //ini, calculate the first k 
        int sum = 0;
        for (int i = 0; i < k; i++) {
            sum += nums[i];
        }
        int max = sum;
        
        //for loop, sliding window
        for (int i = k; i < nums.length; i++) {
            sum = sum + nums[i] - nums[i - k];
            max = Math.max(max, sum);
        }
        
        //return
        return max / 1.0 / k;
    }
}
View Code

 

posted @ 2018-04-21 22:33  苗妙苗  阅读(317)  评论(0编辑  收藏  举报