zoukankan      html  css  js  c++  java
  • leetCode-Maximum Average Subarray I

    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;
        }
    }
  • 相关阅读:
    rpc的几种服务端模型分析
    ASP.NET MVC3在Visual Studio 2010中的变化
    HTML元素的ID和Name属性的区别
    Oracle日期类操作(格式 加减乘 取毫秒)
    快速原型工具
    C#4.0新特性dynamic\可选参数、命名参数
    WCF注册Windows Service
    不要在using语句中调用WCF服务
    C# 4.0 新特性dynamic、可选参数、命名参数等
    Windows内置系统账户Local system/Network service/Local Service
  • 原文地址:https://www.cnblogs.com/kevincong/p/7900343.html
Copyright © 2011-2022 走看看