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.
Mergenums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
Follow up: Can you come up with an algorithm that runs in O(m + n) time?
Solution
Please be adviced that the problem’s description- “The final sorted array should not be returned by the function, but instead be stored inside the array nums1″
C# Solution
Solution1
public class Solution {
public void Merge(int[] nums1, int m, int[] nums2, int n) {
int cnt = 0;
for(int i = m;i<nums1.Length;i++)
{
nums1[i] = nums2[cnt];
cnt++;
}
Array.Sort(nums1);
}
}
The time complexity should be : m-n times + Array.Sort ( based on Quicksort ) ➡ O(n)+O(n log n)
But look at the follow up : “Can you come up with an algorithm that runs in O(m + n) time?”
Maybe we should try another way?
⭐Solution2 (Recommend – two pointer solution)
public class Solution {
public void Merge(int[] nums1, int m, int[] nums2, int n) {
int index = m+n-1; //last index
while(n>0)
{
if(m>0 && nums1[m-1]>nums2[n-1])
{
nums1[index] = nums1[m-1];
m--;
}
else
{
nums1[index] = nums2[n-1];
n--;
}
index --;
}
}
}
What we want to do is combine nums2 n element with nums1 m element to original nums1.
So if we want to combine and sort together, we need to compare the element of two array in iteration.
Time Complexity : O(m + n)
Java Solution
Solution1
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int cnt = 0;
for(int i = m;i<nums1.length;i++)
{
nums1[i] = nums2[cnt];
cnt++;
}
Arrays.sort(nums1);
}
}
Runtime : 1ms
⭐Solution2
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int index = m+n-1; //last index
while(n>0)
{
if(m>0 && nums1[m-1]>nums2[n-1])
{
nums1[index] = nums1[m-1];
m--;
}
else
{
nums1[index] = nums2[n-1];
n--;
}
index --;
}
}
}
ai_front = {"insertion_before":"BEFORE","insertion_after":"AFTER","insertion_prepend":"PREPEND CONTENT","insertion_append":"APPEND CONTENT","insertion_replace_content":"REPLACE CONTENT","insertion_replace_element":"REPLACE ELEMENT","visible":"VISIBLE","hidden":"HIDDEN","fallback":"FALLBACK","automatically_placed":"Automatically placed by AdSense Auto ads code","cancel":"Cancel","use":"Use","add":"Add","parent":"Parent","cancel_element_selection":"Cancel element selection","select_parent_element":"Select parent element","css_selector":"CSS selector","use_current_selector":"Use current selector","element":"ELEMENT","path":"PATH","selector":"SELECTOR"};