Thursday, April 24, 2014

Leetcode: Merge Sorted Array

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

Solution:

If we start adding the elements from the end to the beginning, once an element is inserted it does not have to be moved

public class Solution {
    public void merge(int A[], int m, int B[], int n) {
        int indexA = m;
        int indexB = n;
        while(indexA>0 && indexB>0)
        {
            if(A[indexA-1]>B[indexB-1])
                A[indexA+indexB-1] = A[--indexA];
            else
                A[indexA+indexB-1] = B[--indexB];
        }
        while(indexB>0)
        {
            A[indexB-1]= B[--indexB];
        }
    }
}

No comments :

Post a Comment