【问题标题】:Merge two sorted arrays (leetcode 88): i cant understand how it wont go out of bounds合并两个排序数组(leetcode 88):我无法理解它是如何超出范围的
【发布时间】:2021-09-18 17:19:14
【问题描述】:

我遇到的使用两个指针的解决方案:

var merge = function (nums1, m, nums2, n) {
    let idx1 = m - 1,
        idx2 = n - 1,
        idx3 = m + n - 1;
    while (idx2 >= 0) {
        nums1[idx3--] = nums1[idx1] > nums2[idx2] ? nums1[idx1--] : nums2[idx2--];
    }
};

解决方案有效,但我无法理解,

考虑nums1 = [7,9,11,0,0,0,0], nums2 = [1,2,12,14]

在算法中的某个点,nums1 的索引为 7,而 nums2 的索引为 2,

下一次迭代将导致 idx1 也为-1,从那时起比较语句会发生什么?

(希望我能把问题说清楚,如果我需要用更好的词来表达,请告诉我)

【问题讨论】:

  • "考虑 nums1 = [7,9,11,0,0,0,0], nums2 = [1,2,12,14]," 那么mn 的值?
  • minimum reproducible example
  • 另外,OP,您可以将代码粘贴到 google chrome 中并使用断点来查看代码中任何时候具体会发生什么。你可以用它来计算what will happen at the comparison statement from then on
  • nums1[-1] === undefinedundefined 不大于任何数字。因此idx2 将递减,直到达到0,然后停止循环。

标签: javascript arrays data-structures merge indexoutofboundsexception


【解决方案1】:

这段代码可以在 2 个地方越界,但它工作正常,因为 Javascript 在涉及越界数组访问时有点奇怪:

  1. 它可以在nums1 末尾写入新元素。 Javascript 会自动延长数组以适应新值。
  2. 可以比较nums1[-1] > nums2[idx2]nums1[-1]undefined,所以这个比较总是false,这正是作者想要的。

如果您曾经编写过这样的代码,您应该添加 cmets 来解释其工作原理,因为它依赖于 Javascript 的特性,这些特性不会延续到其他语言中,并且对于阅读代码的每个人来说都不是显而易见的。

【讨论】:

  • 谢谢,我现在对它有了更好的理解。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-22
  • 1970-01-01
  • 2022-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
相关资源
最近更新 更多