Monday, June 22, 2015

Merge Sorted Array | Leetcode

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
 
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

---

Solution: Basic merge algorithm of the merge sort. Main trick is to start filling in the answer from the back of the array. If you try to fill in the answer starting from the front, then you will either need to allocate a new array at the beginning, or push back all the existing elements in the arrays for every out-of-order element insert.

Maintain one pointer for each array to merge. When there is something left in both arrays, compare the values. When either one of the arrays is exhausted, just take elements from the non-empty array until done.
public class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        for (int i = m + n - 1; i >= 0; i--) {
            if (m <= 0) {
                nums1[i] = nums2[--n];
            } else if (n <= 0) {
                nums1[i] = nums1[--m];
            } else {
                if (nums1[m - 1] < nums2[n - 1]) {
                    nums1[i] = nums2[--n];
                } else {
                    nums1[i] = nums1[--m];
                }
            }
        }
    }
}

No comments: