LeetCode 题解工作台
不同三位偶数的数目
给你一个数字数组 digits ,你需要从中选择三个数字组成一个三位偶数,你的任务是求出 不同 三位偶数的数量。 注意 :每个数字在三位偶数中都只能使用 一次 ,并且 不能 有前导零。 示例 1: 输入: digits = [1,2,3,4] 输出: 12 解释: 可以形成的 12 个不同的三位偶数…
4
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们用一个哈希表 记录所有不同的三位偶数,然后枚举所有可能的三位偶数,将其加入哈希表中。 最后返回哈希表的大小即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个数字数组 digits,你需要从中选择三个数字组成一个三位偶数,你的任务是求出 不同 三位偶数的数量。
注意:每个数字在三位偶数中都只能使用 一次 ,并且 不能 有前导零。
示例 1:
输入: digits = [1,2,3,4]
输出: 12
解释: 可以形成的 12 个不同的三位偶数是 124,132,134,142,214,234,312,314,324,342,412 和 432。注意,不能形成 222,因为数字 2 只有一个。
示例 2:
输入: digits = [0,2,2]
输出: 2
解释: 可以形成的三位偶数是 202 和 220。注意,数字 2 可以使用两次,因为数组中有两个 2 。
示例 3:
输入: digits = [6,6,6]
输出: 1
解释: 只能形成 666。
示例 4:
输入: digits = [1,3,5]
输出: 0
解释: 无法形成三位偶数。
提示:
3 <= digits.length <= 100 <= digits[i] <= 9
解题思路
方法一:哈希表 + 枚举
我们用一个哈希表 记录所有不同的三位偶数,然后枚举所有可能的三位偶数,将其加入哈希表中。
最后返回哈希表的大小即可。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def totalNumbers(self, digits: List[int]) -> int:
s = set()
for i, a in enumerate(digits):
if a & 1:
continue
for j, b in enumerate(digits):
if i == j:
continue
for k, c in enumerate(digits):
if c == 0 or k in (i, j):
continue
s.add(c * 100 + b * 10 + a)
return len(s)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate optimizes for distinctness using hash sets.
- question_mark
Observe if the candidate considers leading zeros when enumerating combinations.
- question_mark
Look for awareness of efficient enumeration and hashing techniques to avoid unnecessary checks.
常见陷阱
外企场景- error
Forgetting to exclude leading zeros, which would result in invalid numbers.
- error
Not using a hash set to eliminate duplicate numbers, leading to incorrect counts.
- error
Overcomplicating the approach by not focusing on the problem's brute-force nature and simple constraints.
进阶变体
外企场景- arrow_right_alt
Modify the problem to allow multiple occurrences of each digit to be used in combinations.
- arrow_right_alt
Expand the problem to handle non-even numbers.
- arrow_right_alt
Alter the problem to generate n-digit even numbers instead of just three-digit ones.