LeetCode 题解工作台
最小元素和最大元素的最小平均值
你有一个初始为空的浮点数数组 averages 。另给你一个包含 n 个整数的数组 nums ,其中 n 为偶数。 你需要重复以下步骤 n / 2 次: 从 nums 中移除 最小 的元素 minElement 和 最大 的元素 maxElement 。 将 (minElement + maxEle…
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
我们首先对数组 进行排序,然后从数组的两端开始取元素,分别计算两个元素的和,取最小值。最后将最小值除以 2 作为答案返回即可。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 为数组 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
你有一个初始为空的浮点数数组 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] |
示例 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 <= 50n为偶数。1 <= nums[i] <= 50
解题思路
方法一:排序
我们首先对数组 进行排序,然后从数组的两端开始取元素,分别计算两个元素的和,取最小值。最后将最小值除以 2 作为答案返回即可。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.