LeetCode88——合并两个有序数组

https://leetcode-cn.com/problems/merge-sorted-array/
我的写法:

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int[] nums3 = new int[m + n];
		int i=0,j=0, k=0;
		if(nums2.length == 0) nums3 = nums1;
		
		while(i < m && j<n) {
			
				if(nums1[i] <= nums2[j]) {
					nums3[k] = nums1[i];
					i++;
				}else {
					nums3[k] = nums2[j];
					j++;
				}
				k++;
		}
			
		
	
		while(j < n) {
			nums3[k] = nums2[j];
			k++;
			j++;
		}
		
		while(i < m) {
			nums3[k] = nums1[i];
			k++;
			i++;
		}
		
		
		for(int q=0; q<m + n; q++) {
			nums1[q] = nums3[q];
		}
		
	
    }
}

在这里插入图片描述

还是看下题解的做法吧!
题解1 :

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);
  }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/merge-sorted-array/solution/he-bing-liang-ge-you-xu-shu-zu-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

和我的思路一样,但是调用了系统的复制数组的方法。执行时间比我的快,内存消耗差不多。
在这里插入图片描述
《System.arraycopy为什么快》:https://juejin.cn/post/6844903573545811981

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值