Merge Sorted Array
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]Solution
Easy and not efficient way is to just append the array and then sort it.
public void merge(int[] nums1, int m, int[] nums2, int n) {
for(int i = 0; i < n; i++) {
nums1[m + i] = nums2[i];
}
Arrays.sort(nums1);
}Other solution is to create new array and put there the values. Then just take the values and paste them into num1.
Here is a solution that will do it in-place.
Last updated
Was this helpful?