LeetCode 题解工作台

分割数组中数字的数位

给你一个正整数数组 nums ,请你返回一个数组 answer ,你需要将 nums 中每个整数进行数位分割后,按照 nums 中出现的 相同顺序 放入答案数组中。 对一个整数进行数位分割,指的是将整数各个数位按原本出现的顺序排列成数组。 比方说,整数 10921 ,分割它的各个数位得到 [1,0,…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·模拟

bolt

答案摘要

将数组中的每个数字进行数位分割,然后将分割后的数字依次放入答案数组中。 时间复杂度 $O(n \times \log_{10} M)$,空间复杂度 $O(n \times \log_{10} M)$,其中 为数组 的长度,而 为数组 中的最大值。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个正整数数组 nums ,请你返回一个数组 answer ,你需要将 nums 中每个整数进行数位分割后,按照 nums 中出现的 相同顺序 放入答案数组中。

对一个整数进行数位分割,指的是将整数各个数位按原本出现的顺序排列成数组。

  • 比方说,整数 10921 ,分割它的各个数位得到 [1,0,9,2,1] 。

 

示例 1:

输入:nums = [13,25,83,77]
输出:[1,3,2,5,8,3,7,7]
解释:
- 分割 13 得到 [1,3] 。
- 分割 25 得到 [2,5] 。
- 分割 83 得到 [8,3] 。
- 分割 77 得到 [7,7] 。
answer = [1,3,2,5,8,3,7,7] 。answer 中的数字分割结果按照原数字在数组中的相同顺序排列。

示例 2:

输入:nums = [7,1,3,9]
输出:[7,1,3,9]
解释:nums 中每个整数的分割是它自己。
answer = [7,1,3,9] 。

 

提示:

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 105
lightbulb

解题思路

方法一:模拟

将数组中的每个数字进行数位分割,然后将分割后的数字依次放入答案数组中。

时间复杂度 O(n×log10M)O(n \times \log_{10} M),空间复杂度 O(n×log10M)O(n \times \log_{10} M),其中 nn 为数组 numsnums 的长度,而 MM 为数组 numsnums 中的最大值。

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def separateDigits(self, nums: List[int]) -> List[int]:
        ans = []
        for x in nums:
            t = []
            while x:
                t.append(x % 10)
                x //= 10
            ans.extend(t[::-1])
        return ans
speed

复杂度分析

指标
时间complexity is O(N * D) where N is the length of nums and D is the maximum number of digits in a number. Space complexity is O(N * D) for the resulting array holding all separated digits.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Notice the simplicity masks potential ordering errors when extracting digits.

  • question_mark

    They may hint at handling each integer individually rather than flattening all digits at once.

  • question_mark

    Be ready to discuss trade-offs between string conversion and arithmetic extraction.

warning

常见陷阱

外企场景
  • error

    Reversing the order of digits by accident when using modulo and division without correction.

  • error

    Appending digits to the wrong array or overwriting previous entries.

  • error

    Ignoring single-digit numbers, which should still be included in the output array.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Separate digits for an array containing negative numbers, requiring handling of the sign.

  • arrow_right_alt

    Return the digits in reverse order for each integer while maintaining the overall array order.

  • arrow_right_alt

    Separate digits and filter out zeros or specific digits based on additional constraints.

help

常见问题

外企场景

分割数组中数字的数位题解:数组·模拟 | LeetCode #2553 简单