分割数组中数字的数位
难度:
标签:
题目描述
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)
代码细节讲解
🦆
在题解算法中,将整数转换为字符串后再转换回整数的过程是否会影响算法的执行效率?是否有更直接的方法来分割数位?
▷🦆
如果输入数组`nums`为空,此题解代码是否能正确处理?能否返回一个空数组?
▷🦆
题解中使用了for循环来遍历字符串中的每个字符,这种方法在处理极大的数字时是否高效?
▷