Monday, August 24, 2015

[Merge][Two Poitners] Merge Sorted Array[Facebook]

1. Example
a = [1,2,3,4]
b= [7,8,9,10]
c= merge a and b = [1,2,3,4,7,8,9,10]



2. Implementation
Q1:void => in-place
A1:assume one array size is large enough to accommdate the others.
Q1:hard to insert element into existing array ?
A1:start merging from the last element, backward iterating
num1[m-1]
num2[n-1]
num1[m+n-1]
Q1: one is larger than the other
A1: while to prepend the rest
// NOTE: the reason giving m and n is m is available size and in fact num1's size is larger than m
// NOTE :snippet
int indexNum1 = m-1;
 int indexNum2 = n-1;
 int indexTotal = m+n-1;
while( indexNum2 >=0 )

// Time:O(m+n), Space:O(1)
public void (int[] num1, int m, int[] num2, int n)
{
     // valid the input
     //if (num1== null || m == 0)
     //{
     //     return num2;
     //}
     //if (num2==null || n == 0 ) 
     //{
          //return num1;
     //     return;// void
     //}
     if ( num1 == null || num2 == null )
     {
          return;
     }





     // NOTE: the reason giving m and n is m is available size and in fact num1's size is larger than m
     int indexNum1 = m-1;
     int indexNum2 = n-1;
     int indexTotal = m+n-1;
     //while ( m >=0 && n>=0)
     while (indexNum1 >= 0 && indexNum2 >= 0)
     {
         if (num1[indexNum1] > num2[indexNum2] )
         {
              num1[indexTotal--] = num1[indexNum1--];
         }
         else 
         {
              num1[indexTotal--] = num2[indexNum2--];
         }
     }





     while( indexNum2 >=0 )
     {
         num1[indexTotal--] = num2[indexNum2--];
     }
     while (indexNum1 >= 0)
     {
         num1[indexTotal--] = num1[indexNum1--];
     }
}
3. Similar Ones
(E) Merge two sorted lists

No comments:

Post a Comment