题目地址

解题思路

这一块的题解直接贴官方的解释:
https://leetcode-cn.com/problems/merge-sorted-array/solution/he-bing-liang-ge-you-xu-shu-zu-by-leetco-rrb0/

代码

  1. var merge = function(nums1, m, nums2, n) {
  2. nums1.splice(m, nums1.length - m, ...nums2);
  3. nums1.sort((a, b) => a - b);
  4. };
  1. var merge = function(nums1, m, nums2, n) {
  2. let p1 = 0, p2 = 0;
  3. const sorted = new Array(m + n).fill(0);
  4. var cur;
  5. while (p1 < m || p2 < n) {
  6. if (p1 === m) {
  7. cur = nums2[p2++];
  8. } else if (p2 === n) {
  9. cur = nums1[p1++];
  10. } else if (nums1[p1] < nums2[p2]) {
  11. cur = nums1[p1++];
  12. } else {
  13. cur = nums2[p2++];
  14. }
  15. sorted[p1 + p2 - 1] = cur;
  16. }
  17. for (let i = 0; i != m + n; ++i) {
  18. nums1[i] = sorted[i];
  19. }
  20. };
  1. var merge = function(nums1, m, nums2, n) {
  2. let p1 = m - 1, p2 = n - 1;
  3. let tail = m + n - 1;
  4. var cur;
  5. while (p1 >= 0 || p2 >= 0) {
  6. if (p1 === -1) {
  7. cur = nums2[p2--];
  8. } else if (p2 === -1) {
  9. cur = nums1[p1--];
  10. } else if (nums1[p1] > nums2[p2]) {
  11. cur = nums1[p1--];
  12. } else {
  13. cur = nums2[p2--];
  14. }
  15. nums1[tail--] = cur;
  16. }
  17. };