Monday, March 4, 2013

[LeetCode] Merge Sorted Array


Thought:
Merge from end to front.

Code:
public class Solution {
    public void merge(int A[], int m, int B[], int n) {
        int last = m + n - 1;
        int i = m - 1;
        int j = n - 1;
        while (i >= 0 && j >= 0 ) {
            A[last--] = A[i] > B[j] ? A[i--] : B[j--];
        }
        while (j >= 0) {
            A[last--] = B[j--];
        }        
    }
}

No comments:

Post a Comment