Monday, January 9, 2017

Merge Sorted Array

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.

/*
If we compare two elements from the start of two arrays and put the smaller one to the start of array the nums1, then in the worst case, all the elements in nums1 should move backward in every comparison. Time complexity will be O(m*n)

So we compare two elements from the end of two arrays and put the larger one to the end of the array nums1. Here's end is m+n, for the length of nums1 could be larger than or equal to m+n. We only need to begin at m+n and insert forward after each comparison.
time:O(n), space:O(1)
*/
public class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int index = m + n - 1;
        int i1 = m - 1;
        int i2 = n - 1;
        while (i1 >= 0 && i2 >= 0) {
            if (nums1[i1] > nums2[i2]) {
                nums1[index--] = nums1[i1--];
            } else {
                nums1[index--] = nums2[i2--];
            }
        }
        while (i2 >= 0) {
            nums1[index--] = nums2[i2--];
        }
    }
}

No comments:

Post a Comment