【发布时间】: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]," 那么
m和n的值? -
minimum reproducible example -
另外,OP,您可以将代码粘贴到 google chrome 中并使用断点来查看代码中任何时候具体会发生什么。你可以用它来计算
what will happen at the comparison statement from then on。 -
nums1[-1] === undefined和undefined不大于任何数字。因此idx2将递减,直到达到0,然后停止循环。
标签: javascript arrays data-structures merge indexoutofboundsexception