The merge Sorted array "Leetcode" algorithm, in which Java merges two ordered arrays into an array

Source: Internet
Author: User

A. Merge Sorted Array

Given sorted integer Arrays nums1 and nums2, merge nums2 into nums1 as one sorted Array.

Note:
Assume that nums1 have enough space (size that's greater or equal to m + n) to hold add Itional elements from nums2. The number of elements initialized in nums1 and nums2 is m and n respectively.

Topic:

Given two sorted integer arrays A and B, merge B into a sorted array.
Note: You can assume that a has enough space (greater than or equal to M + N) to hold additional elements from B.

Analysis:

Loop recursive solution, the largest in the final, reverse processing

Method 1:

1  Public classSolution {2      Public voidMergeint[] nums1,intMint[] Nums2,intN) {3        //especially note that the m here is only the number of elements in the NUMS1, not the length of the final first array do not use m=nums1.length, otherwise it will cause data to cross the error4 5         intI=m-1,j=n-1,index=m+n-1;6     7          while(i>=0&&j>=0){8             if(nums1[i]>Nums2[j]) {9                 //a large will put an array of a further behindTennums1[index--]=nums1[i--]; One                A             } -             Else{ -nums1[index--]=nums2[j--]; the                  -             } -         } -          while(i>=0){ +             //a large will put an array of a further behind -nums1[index--]=nums1[i--];  +         } A          while(j>=0){ atnums1[index--]=nums2[j--]; -         } -        -     } -}

Method 2:3 lines of code

 Public class Solution {    publicvoid merge (intint. int int N) {        int i=m-1, j=n-1, k=m+n-1;          while (I>-1 && j>-1) A[k--]= (A[i]>b[j])? a[i--]: b[j--];          while (j>-1)         a[k--]=b[j--];}            }

The merge Sorted array "Leetcode" algorithm, in which Java merges two ordered arrays into an 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.