【发布时间】:2021-06-02 18:42:53
【问题描述】:
我正在解决一些 LeetCode 的各种问题,作为我日常不会遇到的 JavaScript 概念的练习。
从简单的部分开始,我很困惑为什么这个合并数组不起作用?我发现我几乎从不拼接,因为我习惯于迭代并返回一个新元素,而且我很少使用需要直接修改的巨大数据集。
我的 Jasmine 错误如下
检查排序合并
✗ Array values are merged and sorted - Expected $.length = 6 to equal 3. Expected $[2] = 2 to equal 3. Unexpected $[3] = 3 in array. Unexpected $[4] = 5 in array. Unexpected $[5] = 6 in array.
下面是代码。
//////////////////
// INSTRUCTIONS //
//////////////////
// Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
// The number of elements initialized in nums1 and nums2 are m and n respectively.
// You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2.
const nums1 = [1, 2, 3];
const m = 3;
const nums2 = [2, 5, 6];
const n = 3;
const mergeArray = (nums1, nums2) => {
for (let index = 0; index < nums1.length - 1; index++) {
if (nums2[index] >= nums1[index] && nums2[index] < nums1[index+1] ) {
nums1.splice(index, 0, nums2[index]);
}
}
return nums1;
};
module.exports = function () {
describe("Check for Sorted Merge", () => {
it("Array values are merged and sorted", () => {
expect(nums1.concat(nums2).sort()).toEqual(mergeArray(nums1, nums2));
});
});
};
【问题讨论】:
-
请注意:
nums1.concat(nums2).sort()would not necessarily sort integers correctly。它确实适用于您当前的输入,但如果您添加12则不会。 -
首先编写一个不改变输入数组的
mergeArray版本。相反,它应该返回一个新数组。然后,调整程序以改变输入数组。
标签: javascript arrays splice