Leetcode | | 88. Merge Sorted Array

Source: Internet
Author: User

Problem:

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 mand n respectively.

Hide TagsArray of PointersTest instructions: Merge two ordinal groups

Thinking:

(1) First merge and reorder, O (m+n) lo (m+n)

(2) Insert from backward forward, without moving element, O (m+n)

Code

Merge sort

Class Solution {public:    void merge (int a[], int m, int. b[], int n) {for        (int i=0;i<n;i++)            a[m+i]=b[i];        Sort (a,a+m+n);    }};
Insert from backward to forward comparison

Class Solution {public:    void merge (int a[], int m, int b[], int n) {        //Start Typing your C + + solution below
   
    //does not write int main () function        int index = m + n-1;        int aindex = m-1;        int bindex = n-1;        while (0 <= aindex && 0 <= bindex)        {            if (B[bindex] > A[aindex])            {                a[index--] = b[bindex- -];            }            else            {                a[index--] = a[aindex--];            }        }                while (0 <= aindex)        {            a[index--] = a[aindex--];        }                while (0 <= bindex)        {            a[index--] = b[bindex--];}}    ;
   




Leetcode | | 88. Merge Sorted 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.