首页 > 编程语言 > 详细

LeetCode88-合并两个有序数组

时间:2020-12-24 17:19:55      阅读:26      评论:0      收藏:0      [点我收藏+]

 

非商业,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

 

LeetCode88-合并两个有序数组

原文:https://www.cnblogs.com/heibingtai/p/14184491.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!