LeetCode 题解工作台

判断是否可以赢得数字游戏

给你一个 正整数 数组 nums 。 Alice 和 Bob 正在玩游戏。在游戏中,Alice 可以从 nums 中选择所有个位数 或 所有两位数,剩余的数字归 Bob 所有。如果 Alice 所选数字之和 严格大于 Bob 的数字之和,则 Alice 获胜。 如果 Alice 能赢得这场游戏,返回…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·数学

bolt

答案摘要

根据题目描述,只要个位数之和不等于两位数之和,那么 Alice 一定可以选择一个较大的和来获胜。 时间复杂度 ,其中 是数组 的长度。空间复杂度 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

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

解题思路

方法一:求和

根据题目描述,只要个位数之和不等于两位数之和,那么 Alice 一定可以选择一个较大的和来获胜。

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

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

复杂度分析

指标
时间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
psychology

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

判断是否可以赢得数字游戏题解:数组·数学 | LeetCode #3232 简单