leetcode88. 合并两个有序数组

题目

在这里插入图片描述

思路

方法一:直接用接口
python方法sorted()

class Solution(object):
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: void Do not return anything, modify nums1 in-place instead.
        """
        nums1[:] = sorted(nums1[:m] + nums2)


java Arrays.sort()
System.arraycopy(原数组, 原数组开始位置, 目的数组, 目的数组开始位置, 复制长度);

class Solution {
  public void merge(int[] nums1, int m, int[] nums2, int n) {
    System.arraycopy(nums2, 0, nums1, m, n);
    Arrays.sort(nums1);
  }
}

时间复杂度 : O((n+m)log(n+m))。
空间复杂度 : O(1)。

方法二:从前往后双指针
nums1是要输出的数组,不能直接赋值,需要新建一个备份数组。
三个指针,都从头开始,一个指向结果,两个在两数组移动。
nums2和备份数组指针从头开始,比较大小,将小者放进nums1,然后向后移动指针。直到一方指针移动结束。最后再将剩下的数组复制到结果数组中。

class Solution {
  public void merge(int[] nums1, int m, int[] nums2, int n) {
    // Make a copy of nums1.
    int [] nums1_copy = new int[m];
    System.arraycopy(nums1, 0, nums1_copy, 0, m);

    // Two get pointers for nums1_copy and nums2.
    int p1 = 0;
    int p2 = 0;

    // Set pointer for nums1
    int p = 0;

    // Compare elements from nums1_copy and nums2
    // and add the smallest one into nums1.
    while ((p1 < m) && (p2 < n))
      nums1[p++] = (nums1_copy[p1] < nums2[p2]) ? nums1_copy[p1++] : nums2[p2++];

    // if there are still elements to add
    if (p1 < m)
      System.arraycopy(nums1_copy, p1, nums1, p1 + p2, m + n - p1 - p2);
    if (p2 < n)
      System.arraycopy(nums2, p2, nums1, p1 + p2, m + n - p1 - p2);
  }
}


时间复杂度 : O(n + m)。
空间复杂度 : O(m)。

方法三:逆向移动指针
思想其实和方法二类似,主要解决了空间问题,不用额外的备份数组。
因为题目中表示nums1空间为m+n,从后往前,不会覆盖nums1中的数。
三个指针,都从尾巴开始,一个指向结果从m+n-1开始,两个在两数组移动。
比较数组尾部数,较大者存进nums1尾部,指针向前移动,直到一方指针移到头部。再将剩下部分,复制过来。

class Solution {
  public void merge(int[] nums1, int m, int[] nums2, int n) {
    // two get pointers for nums1 and nums2
    int p1 = m - 1;
    int p2 = n - 1;
    // set pointer for nums1
    int p = m + n - 1;

    // while there are still elements to compare
    while ((p1 >= 0) && (p2 >= 0))
      // compare two elements from nums1 and nums2 
      // and add the largest one in nums1 
      nums1[p--] = (nums1[p1] < nums2[p2]) ? nums2[p2--] : nums1[p1--];

    // add missing elements from nums2 ,如果剩下nums1不用移动
    System.arraycopy(nums2, 0, nums1, 0, p2 + 1);
  }
}


时间复杂度 : O(n + m)。
空间复杂度 : O(1)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值