LeetCode 题解工作台
翻转卡片游戏
在桌子上有 n 张卡片,每张卡片的正面和背面都写着一个正数(正面与背面上的数有可能不一样)。 我们可以先翻转任意张卡片,然后选择其中一张卡片。 如果选中的那张卡片背面的数字 x 与任意一张卡片的正面的数字都不同,那么这个数字是我们想要的数字。 哪个数是这些想要的数字中最小的数(找到这些数中的最小值)…
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们注意到,对于位置 ,若 与 元素相同,则一定不满足条件。 因此,我们先找出正面与背面相同的元素,记录在哈希表 中。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
在桌子上有 n 张卡片,每张卡片的正面和背面都写着一个正数(正面与背面上的数有可能不一样)。
我们可以先翻转任意张卡片,然后选择其中一张卡片。
如果选中的那张卡片背面的数字 x 与任意一张卡片的正面的数字都不同,那么这个数字是我们想要的数字。
哪个数是这些想要的数字中最小的数(找到这些数中的最小值)呢?如果没有一个数字符合要求的,输出 0 。
其中, fronts[i] 和 backs[i] 分别代表第 i 张卡片的正面和背面的数字。
如果我们通过翻转卡片来交换正面与背面上的数,那么当初在正面的数就变成背面的数,背面的数就变成正面的数。
示例 1:
输入:fronts = [1,2,4,4,7], backs = [1,3,4,1,3] 输出:2解释:假设我们翻转第二张卡片,那么在正面的数变成了[1,3,4,4,7], 背面的数变成了[1,2,4,1,3]。接着我们选择第二张卡片,因为现在该卡片的背面的数是 2,2 与任意卡片上正面的数都不同,所以 2 就是我们想要的数字。
示例 2:
输入:fronts = [1], backs = [1] 输出:0 解释: 无论如何翻转都无法得到想要的数字,所以返回 0 。
提示:
n == fronts.length == backs.length1 <= n <= 10001 <= fronts[i], backs[i] <= 2000
解题思路
方法一:哈希表
我们注意到,对于位置 ,若 与 元素相同,则一定不满足条件。
因此,我们先找出正面与背面相同的元素,记录在哈希表 中。
接下来,遍历正面与背面的元素,若元素 不在哈希表 中,则更新答案的最小值。
最后,若找到一个满足条件的元素,返回答案,否则返回 。
时间复杂度 ,空间复杂度 。其中 是数组的长度。
class Solution:
def flipgame(self, fronts: List[int], backs: List[int]) -> int:
s = {a for a, b in zip(fronts, backs) if a == b}
return min((x for x in chain(fronts, backs) if x not in s), default=0)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Understanding of hash table usage for efficient lookups
- question_mark
Ability to identify and minimize the good integer through array manipulation
- question_mark
Efficient solution approach with an optimal time complexity
常见陷阱
外企场景- error
Incorrectly handling cases where an integer appears on both the front and back of a card
- error
Overlooking edge cases where no integer is a good integer, leading to a wrong return of 0
- error
Not efficiently managing the time complexity for larger input sizes, leading to performance issues
进阶变体
外企场景- arrow_right_alt
Generalization to handle different ranges of card values
- arrow_right_alt
Optimizing the algorithm for larger input sizes, such as n > 1000
- arrow_right_alt
Variation where flipping conditions are limited or have additional constraints