LeetCode 题解工作台
判断是否可以赢得数字游戏
给你一个 正整数 数组 nums 。 Alice 和 Bob 正在玩游戏。在游戏中,Alice 可以从 nums 中选择所有个位数 或 所有两位数,剩余的数字归 Bob 所有。如果 Alice 所选数字之和 严格大于 Bob 的数字之和,则 Alice 获胜。 如果 Alice 能赢得这场游戏,返回…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·数学
答案摘要
根据题目描述,只要个位数之和不等于两位数之和,那么 Alice 一定可以选择一个较大的和来获胜。 时间复杂度 ,其中 是数组 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个 正整数 数组 nums。
Alice 和 Bob 正在玩游戏。在游戏中,Alice 可以从 nums 中选择所有个位数 或 所有两位数,剩余的数字归 Bob 所有。如果 Alice 所选数字之和 严格大于 Bob 的数字之和,则 Alice 获胜。
如果 Alice 能赢得这场游戏,返回 true;否则,返回 false。
示例 1:
输入:nums = [1,2,3,4,10]
输出:false
解释:
Alice 不管选个位数还是两位数都无法赢得比赛。
示例 2:
输入:nums = [1,2,3,4,5,14]
输出:true
解释:
Alice 选择个位数可以赢得比赛,所选数字之和为 15。
示例 3:
输入:nums = [5,5,5,25]
输出:true
解释:
Alice 选择两位数可以赢得比赛,所选数字之和为 25。
提示:
1 <= nums.length <= 1001 <= nums[i] <= 99
解题思路
方法一:求和
根据题目描述,只要个位数之和不等于两位数之和,那么 Alice 一定可以选择一个较大的和来获胜。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def canAliceWin(self, nums: List[int]) -> bool:
a = sum(x for x in nums if x < 10)
b = sum(x for x in nums if x > 9)
return a != b
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since each number is inspected once to separate digits and compute sums. Space complexity is O(n) for storing single and double-digit groups, though it can be reduced to O(1) with running totals. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Pay attention to array partitioning by single and double-digit numbers.
- question_mark
Notice that summing all numbers of one type is faster than testing combinations.
- question_mark
Check boundary cases like all numbers being single-digit or double-digit.
常见陷阱
外企场景- error
Failing to correctly identify single versus double-digit numbers in the array.
- error
Attempting unnecessary subset sums instead of total sums of each group.
- error
Overlooking edge cases where sums are equal, which does not allow Alice to win.
进阶变体
外企场景- arrow_right_alt
Allow Alice to pick any numbers whose digit count is prime instead of single/double digits.
- arrow_right_alt
Change the winning condition to sum difference >= k instead of strictly greater.
- arrow_right_alt
Include negative numbers in nums to see how sum comparison logic adapts.