LeetCode 题解工作台

最小和分割

给你一个正整数 num ,请你将它分割成两个非负整数 num1 和 num2 ,满足: num1 和 num2 直接连起来,得到 num 各数位的一个排列。 换句话说, num1 和 num2 中所有数字出现的次数之和等于 num 中所有数字出现的次数。 num1 和 num2 可以包含前导 0 。…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 贪心·invariant

bolt

答案摘要

我们先用哈希表或数组 统计 中各个数字出现的次数,用变量 记录 的位数。 接下来,枚举 所有位数 ,将 中的数字按照从小到大的顺序交替地分配给 和 ,记录在一个长度为 的数组 中。最后,返回 中的两个数之和即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个正整数 num ,请你将它分割成两个非负整数 num1 和 num2 ,满足:

  • num1 和 num2 直接连起来,得到 num 各数位的一个排列。
    • 换句话说,num1 和 num2 中所有数字出现的次数之和等于 num 中所有数字出现的次数。
  • num1 和 num2 可以包含前导 0 。

请你返回 num1num2 可以得到的和的 最小 值。

注意:

  • num 保证没有前导 0 。
  • num1 和 num2 中数位顺序可以与 num 中数位顺序不同。

 

示例 1:

输入:num = 4325
输出:59
解释:我们可以将 4325 分割成 num1 = 24 和 num2 = 35 ,和为 59 ,59 是最小和。

示例 2:

输入:num = 687
输出:75
解释:我们可以将 687 分割成 num1 = 68 和 num2 = 7 ,和为最优值 75 。

 

提示:

  • 10 <= num <= 109
lightbulb

解题思路

方法一:计数 + 贪心

我们先用哈希表或数组 cntcnt 统计 numnum 中各个数字出现的次数,用变量 nn 记录 numnum 的位数。

接下来,枚举 numsnums 所有位数 ii,将 cntcnt 中的数字按照从小到大的顺序交替地分配给 num1num1num2num2,记录在一个长度为 22 的数组 ansans 中。最后,返回 ansans 中的两个数之和即可。

时间复杂度 O(n)O(n),空间复杂度 O(C)O(C)。其中 nnnumnum 的位数;而 CCnumnum 中不同数字的个数,本题中 C10C \leq 10

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
    def splitNum(self, num: int) -> int:
        cnt = Counter()
        n = 0
        while num:
            cnt[num % 10] += 1
            num //= 10
            n += 1
        ans = [0] * 2
        j = 0
        for i in range(n):
            while cnt[j] == 0:
                j += 1
            cnt[j] -= 1
            ans[i & 1] = ans[i & 1] * 10 + j
        return sum(ans)
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    The candidate demonstrates understanding of greedy algorithms and sorting techniques.

  • question_mark

    The candidate shows the ability to break down a problem into manageable subproblems.

  • question_mark

    The candidate approaches the problem with the correct choice of sorting and distribution strategy.

warning

常见陷阱

外企场景
  • error

    Not sorting the digits of the number, leading to suboptimal splits.

  • error

    Failing to alternate the digits between `num1` and `num2` effectively.

  • error

    Overcomplicating the solution by trying to use dynamic programming or other complex methods when sorting and a greedy approach are sufficient.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the number has repeating digits?

  • arrow_right_alt

    What if the number is large, near the upper constraint?

  • arrow_right_alt

    How would you modify the approach to handle smaller numbers with fewer digits?

help

常见问题

外企场景

最小和分割题解:贪心·invariant | LeetCode #2578 简单