Why it works
- The largest number of all is the larger of the two last ones, and its place is the last cell. Then the same goes for the rest, so the result is filled from the end, one largest number at a time.
- Filling from the end never erases a number we still need: write is always to the right of i, so it lands only on an empty cell or on a number that has already moved.
- When nums2 runs out, the numbers left in nums1 are already in their places, so the loop stops there.
Complexity
Time O(m + n): each step puts one number in its place. Memory O(1): the merge happens inside nums1, without a third array.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗