LeetCode 题解工作台

子数组最大平均数 I

给你一个由 n 个元素组成的整数数组 nums 和一个整数 k 。 请你找出平均数最大且 长度为 k 的连续子数组,并输出该最大平均数。 任何误差小于 10 -5 的答案都将被视为正确答案。 示例 1: 输入: nums = [1,12,-5,-6,50,3], k = 4 输出: 12.75 解释…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 滑动窗口(状态滚动更新)

bolt

答案摘要

我们维护一个长度为 的滑动窗口,每次计算窗口内的和 ,取最大的和 作为答案。 时间复杂度 ,其中 是数组 的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个由 n 个元素组成的整数数组 nums 和一个整数 k

请你找出平均数最大且 长度为 k 的连续子数组,并输出该最大平均数。

任何误差小于 10-5 的答案都将被视为正确答案。

 

示例 1:

输入:nums = [1,12,-5,-6,50,3], k = 4
输出:12.75
解释:最大平均数 (12-5-6+50)/4 = 51/4 = 12.75

示例 2:

输入:nums = [5], k = 1
输出:5.00000

 

提示:

  • n == nums.length
  • 1 <= k <= n <= 105
  • -104 <= nums[i] <= 104
lightbulb

解题思路

方法一:滑动窗口

我们维护一个长度为 kk 的滑动窗口,每次计算窗口内的和 ss,取最大的和 ss 作为答案。

时间复杂度 O(n)O(n),其中 nn 是数组 numsnums 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
class Solution:
    def findMaxAverage(self, nums: List[int], k: int) -> float:
        ans = s = sum(nums[:k])
        for i in range(k, len(nums)):
            s += nums[i] - nums[i - k]
            ans = max(ans, s)
        return ans / k
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidates should understand how to implement the sliding window technique and avoid brute force solutions.

  • question_mark

    Look for an understanding of maintaining a running sum efficiently during window shifts.

  • question_mark

    Candidates who are familiar with space optimization techniques and avoid unnecessary data structures will perform well.

warning

常见陷阱

外企场景
  • error

    Candidates may incorrectly compute the sum after sliding the window, resulting in incorrect averages.

  • error

    Misunderstanding the sliding window approach could lead to a brute-force solution with O(n*k) complexity.

  • error

    Candidates might forget to handle small edge cases such as when the array has only one element.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider using a sliding window for other array problems, like finding the maximum sum of subarrays.

  • arrow_right_alt

    What if k was dynamic? How would you adjust the sliding window approach to accommodate varying subarray sizes?

  • arrow_right_alt

    Extend the solution to find the subarray with the maximum product instead of the sum.

help

常见问题

外企场景

子数组最大平均数 I题解:滑动窗口(状态滚动更新) | LeetCode #643 简单