88. Merge Sorted Array( JavaScript )

两个有序数组 nums1 和 nums2,把 nums2 按大小放进 nums1。

Example:
  • Input:
    nums1 = [1,2,3,0,0,0], m = 3
    nums2 = [2,5,6], n = 3

  • Output: [1,2,2,3,5,6]

解析:

如果让两个数组从头开始循环,那么插入 nums1 的时候插入的这个位置包括后面的所有数都要向后移一位,数组这样操作是麻烦的。
所以从后开始循环。
比较后大的那个数放在 nums1 末尾。

(The following English translation may not be right -.-)

analyze:

if we compares the item in the two arrays with loop from head to the end, it's so complex to insert the bigger num to the nums1, that means the all items behind the num have to move.
so it's should loop from the end to head, then put the bigger num in the nums1's end.

/**
 * @param {number[]} nums1
 * @param {number} m
 * @param {number[]} nums2
 * @param {number} n
 * @return {void} Do not return anything, modify nums1 in-place instead.
 */
var merge = function(nums1, m, nums2, n) {
  let i = m-1;
  let j = n-1;
  let k = nums1.length - 1;

  while (i >= 0 && j >= 0) {
    if (nums1[i] > nums2[j]) {
      nums1[k] = nums1[i];
      i--;
    } else {
      nums1[k] = nums2[j]
      j--
    }
    k--;
  }
  
  // 当 nums2 比 nums1 长时 
  while (j >= 0) {
    nums1[k--] = nums2[j--]
  }
};
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 8,218评论 0赞 10
  • 一叶而知秋色近。 旁边的梧桐树还依然泛着绿意,可是现在已经是带着金色留白的秋天。很奇怪时间那么快,对于一个不睡觉患...
    绿斜阅读 390评论 0赞 1
  • 为什么那么在意未来 还不是因为有人会来 于是我停留现在 让我看来不那么迫不及待
    雪山飞狐_122阅读 193评论 0赞 2

友情链接更多精彩内容