# LeetCode: Merge Sorted Array Solution

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}// O(m * n)2var merge = function (nums1, m, nums2, n) {3  let i = m4  while (nums2.length) {5    let el = nums2.shift()6    nums1[i] = el7    let j = i8    while (true) {9      if (nums1[j] < nums1[j - 1]) {10        ;[nums1[j], nums1[j - 1]] = [nums1[j - 1], nums1[j]]11        j--12        continue13      }14      break15    }16    i++17  }18}19
20// O(m + n)21var merge = function (nums1, m, nums2, n) {22  let i = m + n - 123  m--24  n--25  while (m >= 0 && n >= 0) {26    if (nums1[m] > nums2[n]) {27      nums1[i--] = nums1[m--]28    } else {29      nums1[i--] = nums2[n--]30    }31  }32  while (n >= 0) {33    nums1[i--] = nums2[n--]34  }35}```

leetcode

array

two pointers

## Next Post

LeetCode: Set Matrix Zeroes

Feb 8, 2021

LeetCode: 3sum

Feb 7, 2021

Search Posts