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.

思路:

由于两个数组大小已知,可以计算从最终数组的总长度,所以可以从大到小的顺序做归并排序。时间复杂度为O(m+n)。

代码:

class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int cur = m-1;
        for(int i = 0; i < n; i++)
        {
            while(cur >= 0 && A[cur] >= B[n-1-i])
            {
                A[cur + n - i] = A[cur--];
            };
            A[cur + n - i] = B[n-1-i];
        }
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11786447
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞