[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 to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

思考:3指针。从后往前遍历。

class Solution {

public:

    void merge(int A[], int m, int B[], int n) {

        int i=m-1;

        int j=n-1;

        int k=m+n-1;

        while(k>=0)

        {

            if(i>=0&&A[i]>=B[j]) 

            {

                A[k]=A[i];

                i--;

                k--;

            }

            else if(j>=0&&A[i]<B[j])

            {

                A[k]=B[j];

                j--;

                k--;

            }

            if(i>=0&&j<0) return;

            if(i<0&&j>=0)

            {

                for(int p=0;p<=j;p++)

                {

                    A[p]=B[p];

                }

                return;

            }

        }

    }

};

2014-03-27 16:53:19

class Solution {

public:

    void merge(int A[], int m, int B[], int n) {

        int i=m-1;

        int j=n-1;

        int k=m+n-1;

        while(i>=0&&j>=0)

        {

            if(A[i]>B[j]) A[k--]=A[i--];

            else A[k--]=B[j--];

        }

        //未考虑m=0的情况

        while(j>=0) A[k--]=B[j--];

    }

};

  

 

你可能感兴趣的:(LeetCode)