88. 合并两个有序数组

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

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        // 思路:
        // 双指针的方式。 【充分利用本身有序的特点】
        // 首先 copy 一份 nums1 出来 [因为最后返回的要是nums1]
        // 用两个指针,一个从 nums1_copy[0] 开始,一个从nums2[0]开始往后
        // 对比哪个跟小,就先放进 nums1
        // 剩余的直接放到nums1 后面即可

        int[] nums1_copy = new int[m];
        System.arraycopy(nums1, 0, nums1_copy, 0, m);

        // nums1_copy 的指针
        int p_copy = 0;
        // nums1 的指针
        int p1 = 0;
        // nums2 的指针
        int p2 = 0;

        while(p_copy < m && p2 < n){
            nums1[p1++] = nums1_copy[p_copy] < nums2[p2]? nums1_copy[p_copy++]:nums2[p2++];
        }
        // 如果 nums2已经全部放到了nums1上,接下来就要把 nums_copy剩余的放到nums1上面去
        if(p_copy < m){
            System.arraycopy(nums1_copy, p_copy, nums1, p_copy+p2, m + n - p_copy - p2);
        }
        // 如果 nums_copy 已经全部放到了nums1上,接下来就要把 nums2 剩余的放到nums1上面去
        if(p2 < n){
            System.arraycopy(nums2, p2, nums1, p_copy+p2, m + n - p_copy - p2);
        }
    }
}

 难点:

1 双指针思维

2 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.要复制的数组元素的数量

简单来说就源数组 src 的第几个 srcPos 开始,复制到目标数组 dest 的第几个 destPos 上面去,一共复制源数组的 length 个
     * @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);
原文地址:https://www.cnblogs.com/junbaba/p/14139556.html