Monday, June 16, 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 m and nrespectively.
public class Solution {//04
    public void merge(int A[], int m, int B[], int n) {
        int a = m-1, b = n-1, i = m+n-1;
        while(a>=0 || b>=0){
            if(b<0) return;
            A[i--] = (a>=0 && A[a]>B[b]) ? A[a--] : B[b--];
        }
    }
}

No comments:

Post a Comment