1. 程式人生 > 實用技巧 >LeetCode88-合併兩個有序陣列

LeetCode88-合併兩個有序陣列

非商業,LeetCode連結附上:

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

進入正題。

題目:

給你兩個有序整數陣列nums1 和 nums2,請你將 nums2 合併到nums1中,使 nums1 成為一個有序陣列。

說明:

初始化nums1 和 nums2 的元素數量分別為m 和 n 。
你可以假設nums1有足夠的空間(空間大小大於或等於m + n)來儲存 nums2 中的元素。

示例:

輸入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3

輸出:[1,2,2,3,5,6]

提示:

-10^9 <= nums1[i], nums2[i] <= 10^9
nums1.length == m + n
nums2.length == n


程式碼實現:

public void merge(int[] nums1, int m, int[] nums2, int n) {

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

        int p1 = 0;
        int p2 = 0;

        int p = 0;
        while(p1 < m && p2 < n) {
            nums1[p++] = temp[p1] < nums2[p2] ? temp[p1++] : nums2[p2++];
        }

        if(p1 < m) {
            System.arraycopy(temp, p1, nums1, p, m + n - p1 - p2);
        }
        if(p2 < n) {
            System.arraycopy(nums2, p2, nums1, p, m + n - p1 - p2);
        }

}
//時間複雜度O(m + n),空間複雜度O(m)


//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>.
     */
    @FastNative
    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

  

分析:

以上解法為“雙指標法、從前往後”進行遍歷並比較賦值;

主要是記錄下System.arraycopy方法的使用。

--End