LeetCode 题解工作台
可被三整除的偶数的平均值
给你一个由正整数组成的整数数组 nums ,返回其中可被 3 整除的所有偶数的平均值。 注意: n 个元素的平均值等于 n 个元素 求和 再除以 n ,结果 向下取整 到最接近的整数。 示例 1: 输入: nums = [1,3,6,10,12,15] 输出: 9 解释: 6 和 12 是可以被 3…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·数学
答案摘要
我们注意到,可被 整除的偶数一定是 的倍数,因此我们只需要遍历数组,统计所有 的倍数的和与个数,然后计算平均值即可。 时间复杂度 ,其中 是数组的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个由正整数组成的整数数组 nums ,返回其中可被 3 整除的所有偶数的平均值。
注意:n 个元素的平均值等于 n 个元素 求和 再除以 n ,结果 向下取整 到最接近的整数。
示例 1:
输入:nums = [1,3,6,10,12,15] 输出:9 解释:6 和 12 是可以被 3 整除的偶数。(6 + 12) / 2 = 9 。
示例 2:
输入:nums = [1,2,4,7,10] 输出:0 解释:不存在满足题目要求的整数,所以返回 0 。
提示:
1 <= nums.length <= 10001 <= nums[i] <= 1000
解题思路
方法一:模拟
我们注意到,可被 整除的偶数一定是 的倍数,因此我们只需要遍历数组,统计所有 的倍数的和与个数,然后计算平均值即可。
时间复杂度 ,其中 是数组的长度。空间复杂度 。
class Solution:
def averageValue(self, nums: List[int]) -> int:
s = n = 0
for x in nums:
if x % 6 == 0:
s += x
n += 1
return 0 if n == 0 else s // n
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Understand how to filter specific conditions in an array
- question_mark
Ability to perform simple mathematical calculations efficiently
- question_mark
Handle edge cases like empty or invalid results
常见陷阱
外企场景- error
Misunderstanding the filtering condition, forgetting that a number must be both even and divisible by 3
- error
Not correctly handling cases where no valid numbers exist
- error
Incorrectly rounding the result, when it should be rounded down to the nearest integer
进阶变体
外企场景- arrow_right_alt
Instead of rounding down, round to the nearest integer
- arrow_right_alt
Use bitwise operations for checking even numbers
- arrow_right_alt
Optimize space complexity by avoiding extra variables