LeetCode 题解工作台

拆分数位后四位数字的最小和

给你一个四位 正 整数 num 。请你使用 num 中的 数位 ,将 num 拆成两个新的整数 new1 和 new2 。 new1 和 new2 中可以有 前导 0 ,且 num 中 所有 数位都必须使用。 比方说,给你 num = 2932 ,你拥有的数位包括:两个 2 ,一个 9 和一个 3 …

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 贪心·invariant

bolt

答案摘要

class Solution: def minimumSum(self, num: int) -> int:

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个四位  整数 num 。请你使用 num 中的 数位 ,将 num 拆成两个新的整数 new1 和 new2 。new1 和 new2 中可以有 前导 0 ,且 num 中 所有 数位都必须使用。

  • 比方说,给你 num = 2932 ,你拥有的数位包括:两个 2 ,一个 9 和一个 3 。一些可能的 [new1, new2] 数对为 [22, 93][23, 92][223, 9] 和 [2, 329] 。

请你返回可以得到的 new1 和 new2 的 最小 和。

 

示例 1:

输入:num = 2932
输出:52
解释:可行的 [new1, new2] 数对为 [29, 23] ,[223, 9] 等等。
最小和为数对 [29, 23] 的和:29 + 23 = 52 。

示例 2:

输入:num = 4009
输出:13
解释:可行的 [new1, new2] 数对为 [0, 49] ,[490, 0] 等等。
最小和为数对 [4, 9] 的和:4 + 9 = 13 。

 

提示:

  • 1000 <= num <= 9999
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
class Solution:
    def minimumSum(self, num: int) -> int:
        nums = []
        while num:
            nums.append(num % 10)
            num //= 10
        nums.sort()
        return 10 * (nums[0] + nums[1]) + nums[2] + nums[3]
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Look for a clear understanding of greedy strategies in number optimization.

  • question_mark

    Candidates should demonstrate the ability to use sorting effectively in algorithm design.

  • question_mark

    The approach should validate that splitting digits and minimizing sums is optimal.

warning

常见陷阱

外企场景
  • error

    Failing to account for leading zeros when forming the two numbers.

  • error

    Not correctly sorting the digits before pairing them.

  • error

    Incorrectly assuming that any random splitting of digits will give the smallest sum.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Handling different ranges of numbers, such as working with more or fewer digits.

  • arrow_right_alt

    Exploring the same problem with a constraint on no leading zeros.

  • arrow_right_alt

    Adjusting the problem to consider non-greedy approaches or more complex number splits.

help

常见问题

外企场景

拆分数位后四位数字的最小和题解:贪心·invariant | LeetCode #2160 简单