Merge Sorted Array

来源:互联网 发布:java安装错误代码1603 编辑:程序博客网 时间:2024/06/10 23:12

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.

这道题从题意看,我们不允许使用新的空间,也就是只能在数组A和B中进行变换。

很简单会想到,相比较,如果B比A的小,A整个数组向后移,但是这样的算法复杂度比O(n^2)要大。有没有别的方法呢?

我们知道我们所需要的数组的大小是m+n,那么很显然我们可以从数组后面进行比较。这样就避免了移动所带来的时间消耗。算法复杂度为O(m+n)

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


0 0
原创粉丝点击