88. Merge two ordered arrays (implemented in java) --LeetCode

table of Contents

topic: 

Solution 1: Violence

Solution 2: Double pointer (new array)

Solution 3: Double pointer (do not create a new array)


topic: 

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

Give you two ordered integer arrays nums1 and nums2. Please merge nums2 into nums1 to make nums1 an ordered array.

 

Description:

  • Initialize the number of elements of nums1 and nums2 to m and n respectively.
  • You can assume that nums1 has enough space (the size of the space is greater than or equal to m + n) to store the elements in nums2.

 

Example:

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

Output: [1,2,2,3,5,6]

prompt:

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

 

Solution 1: Violence

/**
 * 思路:
 * 把nums2的元素放入后用Arrays的sort方法排序
 */
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int index=0;
        for (int i=m;m<nums1.length;m++){
            nums1[m]=nums2[index++];
        }
        Arrays.sort(nums1);
    }

Time complexity: O n logn

Space complexity: O1

Solution 2: Double pointer (new array)

/**
 * 思路:
 * 把nums1前m个元素放入新数组nums1_copy
 * 比较nums1_copy和nums2的元素,小的放入nums1
 * 如果nums1_copy的元素用完,就把nums2的元素全拷贝到nums1的剩余位置中。反之亦然
 */
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int nums1_copy[]=new int[m];
        System.arraycopy(nums1,0,nums1_copy,0,m);
        int i=0,j=0;
        for (int index=0;index<nums1.length;index++){
            if (i==m) {
                System.arraycopy(nums2, j, nums1, index, n - j);
                break;
            }
            else if (j==n) {
                System.arraycopy(nums1_copy, i, nums1, index, m - i);
                break;
            }
            else if (nums1_copy[i]<nums2[j])nums1[index]=nums1_copy[i++];
            else if (nums1_copy[i]>nums2[j])nums1[index]=nums2[j++];
        }
    }

Time complexity: On

Space complexity: On

 

Solution 3: Double pointer (do not create a new array)

/**
 * 思路:
 * 从后往前
 * 利用2个数组都排好序的条件,从nums1的m开始往前遍历,从nums2的n开始往前遍历
 * 比较两个元素,谁大放到nums1的末尾
 * 如果nums2用完,直接结束,nums1就排好序了
 * 如果nums1用完,需要将nums2的元素全放入剩余的位置中
 */
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        m--;
        n--;
        for (int index = nums1.length - 1; index >= 0; index--) {
            if (m < 0) nums1[index] = nums2[n--];
            else if (n < 0) break;
            else if (nums1[m] > nums2[n]) {
                nums1[index] = nums1[m--];
            } else {
                nums1[index] = nums2[n--];
            }
        }
    }

Time complexity: On

Space complexity: O1

Guess you like

Origin blog.csdn.net/qq_38783664/article/details/110388857