【LeetCode從零單排】No88.Merge Sorted Array

李博Garvin發表於2015-03-02

題目

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.

ps:下面的解法非常巧妙,我也沒想到,是借鑑leet裡面某大神的程式碼。


程式碼

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




/********************************

* 本文來自部落格  “李博Garvin“

* 轉載請標明出處:http://blog.csdn.net/buptgshengod

******************************************/



相關文章