LeetCode 题解工作台
分块数组
给定一个数组 arr 和一个块大小 size ,返回一个 分块 的数组。 分块 的数组包含了 arr 中的原始元素,但是每个子数组的长度都是 size 。如果 arr.length 不能被 size 整除,那么最后一个子数组的长度可能小于 size 。 你可以假设该数组是 JSON.parse 的输…
0
题型
2
代码语言
0
相关题
当前训练重点
简单 · chunk·数组·core·interview·pattern
答案摘要
function chunk(arr: any[], size: number): any[][] { const ans: any[][] = [];
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 chunk·数组·core·interview·pattern 题型思路
题目描述
给定一个数组 arr 和一个块大小 size ,返回一个 分块 的数组。
分块 的数组包含了 arr 中的原始元素,但是每个子数组的长度都是 size 。如果 arr.length 不能被 size 整除,那么最后一个子数组的长度可能小于 size 。
你可以假设该数组是 JSON.parse 的输出结果。换句话说,它是有效的JSON。
请你在不使用 lodash 的函数 _.chunk 的情况下解决这个问题。
示例 1:
输入:arr = [1,2,3,4,5], size = 1
输出:[[1],[2],[3],[4],[5]]
解释:数组 arr 被分割成了每个只有一个元素的子数组。
示例 2:
输入:arr = [1,9,6,3,2], size = 3
输出:[[1,9,6],[3,2]]
解释:数组 arr 被分割成了每个有三个元素的子数组。然而,第二个子数组只有两个元素。
示例 3:
输入:arr = [8,5,3,2,6], size = 6 输出:[[8,5,3,2,6]] 解释:size大于arr.length,因此所有元素都在第一个子数组中。
示例 4:
输入:arr = [], size = 1 输出:[] 解释:没有元素需要分块,因此返回一个空数组。
提示:
arr是表示数组的字符串。2 <= JSON.stringify(arr).length <= 1051 <= size <= arr.length + 1
解题思路
方法一
/**
* @param {Array} arr
* @param {number} size
* @return {Array[]}
*/
var chunk = function (arr, size) {
const ans = [];
for (let i = 0, n = arr.length; i < n; i += size) {
ans.push(arr.slice(i, i + size));
}
return ans;
};
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since each element is processed once. Space complexity is O(n) for the resulting chunked array. Choice of slicing or shifting may affect constant factors but not asymptotic behavior. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
They may ask about handling the last chunk when arr.length is not divisible by size.
- question_mark
Watch for edge cases where size is greater than arr.length.
- question_mark
They may probe in-place modification vs. creating a new array for chunking.
常见陷阱
外企场景- error
Failing to handle the last chunk correctly when it contains fewer elements than size.
- error
Modifying the original array unintentionally when using shift-based approaches.
- error
Incorrectly calculating slice indices leading to missing or repeated elements.
进阶变体
外企场景- arrow_right_alt
Chunking multidimensional arrays while preserving nested structure.
- arrow_right_alt
Dynamic chunk size where size changes based on runtime conditions.
- arrow_right_alt
Reversing the order of chunks after splitting for alternate interview constraints.