Merge Sorted Array

Easy

Given two sorted integer arrays nums1 _and _nums2, merge _nums2 _into _nums1 _as one sorted array.

Note:

  • The number of elements initialized in nums1 and nums2 are m and n respectively.

  • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from 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]

Analysis

这一题的trick在于,因为是数组,不适合插入操作,所以从nums1[]的末端开始反向填充,就可以避免数据大量搬运。

Solution

One pass - O(n) time, O(1) space - (2ms, 100%)

Another more concise implementation (2ms, 100%)

Last updated

Was this helpful?