Merge Two Sorted Arrays

Medium~15 min

Given two sorted integer arrays nums1 and nums2, merge them into a single sorted array and return it.

Both input arrays are sorted in non-decreasing order. The result should also be sorted in non-decreasing order.

For example, merging [1, 3, 5] and [2, 4, 6] produces [1, 2, 3, 4, 5, 6].

Examples

Example 1
Input: nums1 = [1, 3, 5], nums2 = [2, 4, 6]
Output: [1, 2, 3, 4, 5, 6]
Explanation: Elements from both arrays are interleaved in sorted order.
Example 2
Input: nums1 = [1, 2, 3], nums2 = [4, 5, 6]
Output: [1, 2, 3, 4, 5, 6]
Explanation: All elements in nums1 are smaller, so nums2 is simply appended.
Example 3
Input: nums1 = [], nums2 = [1, 2, 3]
Output: [1, 2, 3]
Explanation: One array is empty, so the result is the other array.

Constraints

  • 0 <= nums1.length, nums2.length <= 10^4
  • -10^9 <= nums1[i], nums2[i] <= 10^9
  • Both arrays are sorted in non-decreasing order.
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run