繁体   English   中英

合并排序数组 Javascript

[英]Merging Sorted Array Javascript

我正在解决一些 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));
    });
  });
};

也许是这样的? 由于 arrays 都已排序,因此我们不需要将每个 m 元素与每个 n 元素进行比较。 我们可以通过跟踪起点来节省一些时间复杂度,并在每次从 nums2 中找到 n 元素的位置时更新它。 希望这是有道理的,但如果没有,我可以尝试更彻底地解释它。

 const nums1 = [1, 2, 3]; // will always be sorted const m = 3; const nums2 = [2, 5, 6]; // will always be sorted const n = 4; const mergeArray = (nums1, nums2) => { let start_idx = 0; for (let num of nums2) { for (let idx = start_idx; idx < nums1.length; idx++){ if (num <= nums1[idx]) { nums1.splice(idx, 0, num); start_idx = idx; break; } if (idx == nums1.length - 1){ nums1.push(num); start_idx = idx; break; } } } return nums1; }; const res1 = nums1.concat(nums2).sort((a,b) => ab); const res2 = mergeArray(nums1, nums2); console.log(res1, res2); //JSON.stringify not ideal for arr/object comparison, but it works here for a quick check: console.assert(JSON.stringify(res1) == JSON.stringify(res2), "sorts are not identical");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM