LeetCode 题解工作台

最小元素和最大元素的最小平均值

你有一个初始为空的浮点数数组 averages 。另给你一个包含 n 个整数的数组 nums ,其中 n 为偶数。 你需要重复以下步骤 n / 2 次: 从 nums 中移除 最小 的元素 minElement 和 最大 的元素 maxElement 。 将 (minElement + maxEle…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 双·指针·invariant

bolt

答案摘要

我们首先对数组 进行排序,然后从数组的两端开始取元素,分别计算两个元素的和,取最小值。最后将最小值除以 2 作为答案返回即可。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 为数组 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

你有一个初始为空的浮点数数组 averages。另给你一个包含 n 个整数的数组 nums,其中 n 为偶数。

你需要重复以下步骤 n / 2 次:

  • nums 中移除 最小 的元素 minElement 最大 的元素 maxElement
  • (minElement + maxElement) / 2 加入到 averages 中。

返回 averages 中的 最小 元素。

 

示例 1:

输入: nums = [7,8,3,4,15,13,4,1]

输出: 5.5

解释:

步骤 nums averages
0 [7,8,3,4,15,13,4,1] []
1 [7,8,3,4,13,4] [8]
2 [7,8,4,4] [8,8]
3 [7,4] [8,8,6]
4 [] [8,8,6,5.5]
返回 averages 中最小的元素,即 5.5。

示例 2:

输入: nums = [1,9,8,3,10,5]

输出: 5.5

解释:

步骤 nums averages
0 [1,9,8,3,10,5] []
1 [9,8,3,5] [5.5]
2 [8,5] [5.5,6]
3 [] [5.5,6,6.5]

示例 3:

输入: nums = [1,2,3,7,8,9]

输出: 5.0

解释:

步骤 nums averages
0 [1,2,3,7,8,9] []
1 [2,3,7,8] [5]
2 [3,7] [5,5]
3 [] [5,5,5]

 

提示:

  • 2 <= n == nums.length <= 50
  • n 为偶数。
  • 1 <= nums[i] <= 50
lightbulb

解题思路

方法一:排序

我们首先对数组 nums\textit{nums} 进行排序,然后从数组的两端开始取元素,分别计算两个元素的和,取最小值。最后将最小值除以 2 作为答案返回即可。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(logn)O(\log n)。其中 nn 为数组 nums\textit{nums} 的长度。

1
2
3
4
5
6
class Solution:
    def minimumAverage(self, nums: List[int]) -> float:
        nums.sort()
        n = len(nums)
        return min(nums[i] + nums[-i - 1] for i in range(n // 2)) / 2
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Tests the candidate's understanding of sorting and its role in pairing elements.

  • question_mark

    Evaluates familiarity with two-pointer techniques and invariant tracking.

  • question_mark

    Checks if the candidate can optimize average calculations by focusing on sorting and pairing.

warning

常见陷阱

外企场景
  • error

    Failing to sort the array before pairing the elements.

  • error

    Not properly updating the minimum average during the two-pointer scanning.

  • error

    Ignoring edge cases, such as arrays with the smallest possible length.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Change the problem to return the maximum average instead of the minimum.

  • arrow_right_alt

    Modify the problem to handle arrays of odd length.

  • arrow_right_alt

    Adjust the problem to calculate the sum of all averages instead of the minimum.

help

常见问题

外企场景

最小元素和最大元素的最小平均值题解:双·指针·invariant | LeetCode #3194 简单