Wednesday, July 3, 2019

88. Merge Sorted Array

Here is the link.

Since it is an easy level algorithm, I just took the straightforward the solution to merge two sorted arrays.
Here are highlights:
  1. Calculate the merged array's length;
  2. Copy backward to the merged array, from each end of the two arrays to start to merge.
public class Solution {
    public void Merge(int[] nums1, int m, int[] nums2, int n)
        {
            if (nums1 == null || nums2 == null)
                return;

            var length = m + n;

            var end1 = m - 1;
            var end2 = n - 1;

            var index = length - 1;
            while(index >= 0)
            {
                var moveFirst = false;
                if (end1 < 0)
                {
                    moveFirst = false;
                }
                else if (end2 < 0)
                {
                    moveFirst = true;
                }
                else
                {
                    var current1 = nums1[end1];
                    var current2 = nums2[end2];
                    moveFirst = current1 > current2;
                }

                if (moveFirst)
                {
                    nums1[index] = nums1[end1];
                    end1--;
                }
                else
                {
                    nums1[index] = nums2[end2];
                    end2--;
                }

                index--;
            }
    }
}


No comments:

Post a Comment