数据结构和算法:合并两个有序数组

Leetcode88:合并两个有序数组

链接: https://leetcode-cn.com/problems/merge-sorted-array/.

给定两个有序证书数组nums1和nums2,将nums2合并到nums1中,使得nums1成为一个有序数组
说明:
1,初始化nums1和nums2的元素数量分别位m和n;
2,可以假设nums1有足够多的空间来保存nums2的元素

解题思路
显然根据说明2,题目要求的最优解法是应该原地排序。
设定指针 len1len 指向nums1的尾部,设定一个指针len2指向nums2的尾部;
再分别从nums1和nums2开始向前遍历,比较指针指向的元素的大小,因为是从后往前插入,大的那个元素插入数组,同时指针向前进一个。

// An highlighted block
class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
       	//因为m和n分别位数组的长度,所以尾指针应该-1
       	int len1 = m - 1;
       	int len2 = n - 1;
       	int len = m + n - 1;
       	//当nums1或者nums2有一个遍历完,即退出循环
       	while(len1 >= 0 && len2 >= 0){
       		nums1[len--] = nums1[len1]>nums2[len2]?nums1[len1--]:nums2[len2--];
       	}
       	//如果此时len2<0.但是len1>=0.
       	//因为是再nums1的数组原地排序,所以不用再处理
    	//如果len1<0,那么就把剩下的元素拷贝到nums1中
    	System.arraycopy(nums2 , 0, nums1 , 0, len2+1);
    }
}

关于System.arraycopy()的源码阅读

     * @param      src      the source array.
     * @param      srcPos   starting position in the source array.
     * @param      dest     the destination array.
     * @param      destPos  starting position in the destination data.
     * @param      length   the number of array elements to be copied.
     * @exception  IndexOutOfBoundsException  if copying would cause
     *               access of data outside array bounds.
     * @exception  ArrayStoreException  if an element in the <code>src</code>
     *               array could not be stored into the <code>dest</code> array
     *               because of a type mismatch.
     * @exception  NullPointerException if either <code>src</code> or
     *               <code>dest</code> is <code>null</code>.
     */
    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值