码迷,mamicode.com
首页 > 其他好文 > 详细

leetCode-Maximum Average Subarray I

时间:2017-11-26 21:04:37      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:temp   esc   element   span   range   better   min   [1]   length   

Description:
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].

My Solution:

class Solution {
    public double findMaxAverage(int[] nums, int k) {
       int max = Integer.MIN_VALUE;
       int len = nums.length;
       int temp = 0;
       if(len == k){
            for(int num : nums){
                temp += num;
            }
           return (temp * 1.0)/k;
        }
        for(int i = 0;i <= len - k;i++){
            temp = 0;
            for(int j = i;j < i + k;j++){
                temp += nums[j];
            }
            if(temp > max){
                max = temp;
            }
        }
        return (max * 1.0) / k;
    }
}

Better Solution1:

//sum[i]存储的是nums前i+1个元素之和
//sum[i] -sum[i - k]表示以i为最后一个元素,k个元素之和
public class Solution {
    public double findMaxAverage(int[] nums, int k) {
        int[] sum = new int[nums.length];
        sum[0] = nums[0];
        for (int i = 1; i < nums.length; i++)
        sum[i] = sum[i - 1] + nums[i];
        double res = sum[k - 1] * 1.0 / k;
        for (int i = k; i < nums.length; i++) {
            res = Math.max(res, (sum[i] - sum[i - k]) * 1.0 / k);
        }
        return res;
    }
}

Better Solution2:

public class Solution {
//先计算出0开始的前k个元素之和,由于nums[1]+nums[2]...nums[k]= nums[0]+nums[1]+...nums[k - 1]+nums[k] - nums[0],利用这个公式一直以nums[i]为最后一个元素滑动
    public double findMaxAverage(int[] nums, int k) {
        double sum=0;
        for(int i=0;i<k;i++)
            sum+=nums[i];
        double res=sum;
        for(int i=k;i<nums.length;i++){
            sum+=nums[i]-nums[i-k];
                res=Math.max(res,sum);
        }
        return res/k;
    }
}

leetCode-Maximum Average Subarray I

标签:temp   esc   element   span   range   better   min   [1]   length   

原文地址:http://www.cnblogs.com/kevincong/p/7900343.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!