Leetcode_merge-sorted-array(updated c++ and python version)

来源:互联网 发布:淘宝优惠券群怎么加入 编辑:程序博客网 时间:2024/05/19 06:50

地址:http://oj.leetcode.com/problems/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 andn respectively.

思路:题目肯定不希望我们把B的数据直接填到A的尾部然后用STL的sort一下。那就一个一个的比较好了。每次A的当前元素比B的当前元素大时,数组A整体后移一位。同时A的长度也应该加一。且无论两个数组的当前元素大小如何,A的遍历下标m都要加1.


参考代码:

class Solution {public:    void merge(int A[], int m, int B[], int n) {        int pa = 0, pb = 0;        for(; pa<m && pb<n; )        {            if(A[pa]>B[pb])            {                for(int i = m; i>pa; --i)                {                    A[i]=A[i-1];                }                A[pa] = B[pb];                ++m;                ++pb;            }            ++pa;        }        while(pb<n)        {            A[m++] = B[pb++];        }    }};


//SOLUTION TWO, which is better.
class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        if(!n)
            return;
        if(!m)
        {
            for(int i = 0; i<n; ++i)
                A[i] = B[i];
            return;
        }
        int i = m-1, j = n-1;
        while(i>=0 && j>=0)
        {
            if(A[i]>=B[j])
                A[i+j+1] = A[i--];
            else
                A[i+j+1] = B[j--];
        }
        if(j<0)
            return;
        for(; j>=0; --j)
            A[j] = B[j];
    }
};


Python:

class Solution:
    # @param A a list of integers
    # @param m an integer, length of A
    # @param B a list of integers
    # @param n an integer, length of B
    # @return nothing
    def merge(self, A, m, B, n):
        if not B or not n:
            return;
        if not A:
            A = B[:]
        la = m-1
        lb = n-1
        while la>=0 and lb>=0:
            if A[la]>=B[lb]:
                A[la+lb+1] = A[la]
                la -= 1
            else:
                A[la+lb+1] = B[lb]
                lb -= 1
        if la<0:
            while lb>=0:
                A[lb]=B[lb]
                lb -= 1

0 0