LeetCode 题解工作台

可被三整除的偶数的平均值

给你一个由正整数组成的整数数组 nums ,返回其中可被 3 整除的所有偶数的平均值。 注意: n 个元素的平均值等于 n 个元素 求和 再除以 n ,结果 向下取整 到最接近的整数。 示例 1: 输入: nums = [1,3,6,10,12,15] 输出: 9 解释: 6 和 12 是可以被 3…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·数学

bolt

答案摘要

我们注意到,可被 整除的偶数一定是 的倍数,因此我们只需要遍历数组,统计所有 的倍数的和与个数,然后计算平均值即可。 时间复杂度 ,其中 是数组的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个由正整数组成的整数数组 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 <= 1000
  • 1 <= nums[i] <= 1000
lightbulb

解题思路

方法一:模拟

我们注意到,可被 33 整除的偶数一定是 66 的倍数,因此我们只需要遍历数组,统计所有 66 的倍数的和与个数,然后计算平均值即可。

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

1
2
3
4
5
6
7
8
9
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
speed

复杂度分析

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

面试官常问的追问

外企场景
  • 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

warning

常见陷阱

外企场景
  • 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

swap_horiz

进阶变体

外企场景
  • 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

help

常见问题

外企场景

可被三整除的偶数的平均值题解:数组·数学 | LeetCode #2455 简单