2014年10月18日星期六

[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.
指针题,其实就是在考察inplace的操作。
    public void merge(int A[], int m, int B[], int n) {
        int endA = m - 1;
        int endB = n - 1;
        int end = m + n - 1;
        while(endA >= 0 && endB >= 0) {
            if(A[endA] > B[endB])
                A[end--] = A[endA--];
            else 
                A[end--] = B[endB--];
        }
        while(endB >= 0)
            A[end--] = B[endB--];
    }

没有评论:

发表评论