Problem
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note: You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
Similar Problem
You are given two integer arrays nums1
and nums2
, sorted in non-decreasing order, and two integers m
and n
, representing the number of elements in nums1
and nums2
respectively.
Merge nums1
and nums2
into a single array sorted in non-decreasing order.
This is similar to Merge Two Sorted Linked Lists.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
The key to solve this problem is moving element of A and B backwards. If B has some elements left after A is done, also need to handle that case.
Method 1 - Merge Sort
The idea is to start from end, by moving elements from A and B. If B has some elements left after A is done, also need to handle that case.
Code
|
|
Complexity
- ⏰ Time complexity:
O (m+n)
, where size of A as m and size of B as n. So , a linear time algorithm. - 🧺 Space complexity:
O(1)
Problem 2 - What if We don’t Have Extra Space in Second Array
Problem
Given two integer arrays A and B sorted in increasing order, merge A and B into a single sorted array C in increasing order.
Examples
|
|
Solution
Then this becomes easier problem. We can just iterate on the array from start as well:
|
|