(Daily algorithm) Leetcode--Merge Sorted Array (merge ordered array)

Source: Internet
Author: User




Given sorted integer arrays A and B, merge B into a as one sorted array.

Note:
You could assume that A have enough space (size that's greater or equal to m + n) to the hold additional Eleme NTS from B. The number of elements initialized in A and B is m andn respectively.

According to the inertia idea of the merge sort, because the merge sort is given the two intervals of an array, the O (n) size of the auxiliary space is usually used. Ideas are as follows:


Class Solution {public:    void merge (int a[], int m, int b[], int n) {        int temp[m+n];        int i = 0, j = 0, t = 0;        while (I < m && J < N)        {            if (A[i] < b[j])                temp[t++] = a[i++];            else                temp[t++] = b[j++];        }        while (I < m)            temp[t++] = a[i++];        while (J < N)            temp[t++] = b[j++];        while (--t >= 0)            a[t] = temp[t];    }};

But the conditions given in the above topics are more flexible, so you can use the tail interpolation method, which eliminates the need for additional space overhead and is more concise in understanding:


Class Solution {public:    void merge (int a[], int m, int b[], int n) {        int ia = m-1, ib = n-1, icur = m + n-1; While        (ia >= 0 && ib >= 0)            a[icur--] = A[ia] > B[ib]? a[ia--]: b[ib--];        while (IB >=0)            a[icur--] = b[ib--];    }};


(Daily algorithm) Leetcode--Merge Sorted Array (merge ordered array)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.