88 Merge Sorted Array

1. Question

Given two sorted integer arraysnums1andnums2, mergenums2intonums1as one sorted array.

Note: You may assume thatnums1has enough space (size that is greater or equal tom+n) to hold additional elements fromnums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

2. Implementation

(1) Two Pointers

public class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int index1 = m - 1, index2 = n - 1;
        int k = m + n - 1;

        while (index1 >= 0 && index2 >= 0) {
            nums1[k--] = nums1[index1] > nums2[index2] ? nums1[index1--] : nums2[index2--];
        }

        while (index2 >= 0) {
            nums1[k--] = nums2[index2--];
        }
    }
}

3. Time & Space Complexity

时间复杂度O(m + n), m为nums1的长度,n为nums2的长度,空间复杂度O(1)

Last updated