leetcode
leetcode 2201 ~ 2250
分割数组中数字的数位

分割数组中数字的数位

难度:

标签:

题目描述

Given an array of positive integers nums, return an array answer that consists of the digits of each integer in nums after separating them in the same order they appear in nums.

To separate the digits of an integer is to get all the digits it has in the same order.

  • For example, for the integer 10921, the separation of its digits is [1,0,9,2,1].

 

Example 1:

Input: nums = [13,25,83,77]
Output: [1,3,2,5,8,3,7,7]
Explanation: 
- The separation of 13 is [1,3].
- The separation of 25 is [2,5].
- The separation of 83 is [8,3].
- The separation of 77 is [7,7].
answer = [1,3,2,5,8,3,7,7]. Note that answer contains the separations in the same order.

Example 2:

Input: nums = [7,1,3,9]
Output: [7,1,3,9]
Explanation: The separation of each integer in nums is itself.
answer = [7,1,3,9].

 

Constraints:

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

代码结果

运行时间: 24 ms, 内存: 16.3 MB


/*
 * 思路:
 * 使用Java Stream API,将每个整数转为字符串后分割其数位,并将所有数位按顺序收集到答案数组中。
 */

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Solution {
    public int[] separateDigits(int[] nums) {
        return Arrays.stream(nums)
                     .mapToObj(String::valueOf)
                     .flatMapToInt(numStr -> numStr.chars().map(Character::getNumericValue))
                     .toArray();
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] nums = {13, 25, 83, 77};
        int[] result = sol.separateDigits(nums);
        for (int i : result) {
            System.out.print(i + " ");
        }
    }
}

解释

方法:

题解的核心思想是遍历整数数组 `nums`,将每个整数转换为字符串,再将字符串中的每个字符转换回整数,并逐个添加到结果数组 `result` 中。这样可以确保整数的数位按原顺序分割并添加到结果数组中。

时间复杂度:

O(n)

空间复杂度:

O(n)

代码细节讲解

🦆
在题解算法中,将整数转换为字符串后再转换回整数的过程是否会影响算法的执行效率?是否有更直接的方法来分割数位?
是的,将整数转换为字符串然后再转换回整数的过程确实会影响算法的执行效率。每次转换都涉及到内存分配和额外的运算,尤其是在处理大数据量时。更直接的方法可以是使用数学方法直接从整数中提取每一位。例如,可以通过循环使用取模操作(%10)来获取最低位,然后使用整除操作(//10)来移除这个最低位。这种方法避免了字符串转换的开销,从而可以更高效地处理数字。
🦆
如果输入数组`nums`为空,此题解代码是否能正确处理?能否返回一个空数组?
是的,如果输入数组`nums`为空,此题解代码会正确处理并返回一个空数组。因为代码中的for循环将不会执行任何迭代,因此`result`数组将保持为空,最终返回的也是一个空数组。这意味着这段代码能够正确处理空输入的情况。
🦆
题解中使用了for循环来遍历字符串中的每个字符,这种方法在处理极大的数字时是否高效?
在处理极大的数字时,将数字转换为字符串并遍历每个字符的方法相对较不高效。字符串的创建和遍历都涉及额外的内存和时间开销。尤其是在数字非常大时,字符串操作的开销也会随之增大。使用数学方法(如前一个问题所述的取模和整除)直接操作数字通常更加高效,因为它避免了字符串处理的开销,并且可以更直接地访问数字的每一位。

相关问题