📘
Merge Sorted Array
EasyArrays & Strings
You are given two sorted integer arrays nums1 and nums2, and integers m and n representing the number of elements in each.
Merge nums2 into nums1 in-place so that nums1 is sorted. nums1 has length m + n with the last n elements set to 0 (placeholders).
Output the merged array as space-separated integers.
Example:
Input:
1,2,3,0,0,0 3 2,5,6 3
Output:
1 2 2 3 5 6
Reasoning:
- The input array
nums1is[1, 2, 3, 0, 0, 0]withm = 3valid elements, andnums2is[2, 5, 6]withn = 3elements. - We merge
nums2intonums1in-place, starting from the end of both arrays, comparing elements and placing the larger one at the end ofnums1. - The merge process involves iterating through both arrays, resulting in the following steps:
- Comparing
3fromnums1and6fromnums2, placing6at the end ofnums1. - Comparing
2fromnums1and5fromnums2, placing5at the second last position ofnums1. - Comparing
2fromnums1and2fromnums2, placing2at the third last position ofnums1, and the remaining2fromnums1is placed before it.
- Comparing
- The final output is the merged and sorted array
[1, 2, 2, 3, 5, 6].
Constraints:
- 0 <= m, n <= 200
- 1 <= m + n <= 200
- -10^9 <= nums1[i], nums2[i] <= 10^9
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.