"Leetcode-Interview algorithm classic-java Implementation" "088-merge Sorted Array (merge sorted array)"

Source: Internet
Author: User

"088-merge Sorted Array (merge sorted array)" "leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index" Original Question

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 additional elements from NUMS2 . The number of elements initialized in Nums1 and Nums2 is M and N respectively.

Main Topic

Given two sorted arrays, the merging of two arrays is also ordered after merging, and the merged results are stored in NUMS1. There is enough space in the NUMS1 to accommodate the NUMS2.

Thinking of solving problems

Start merging from the last position in the two arrays, looking for the larger of the two numbers to move to the positive position, moving the position value of the move forward one position, and then doing the same until all the elements have finished processing.

Code Implementation

Algorithm implementation class

 Public classSolution { Public void Merge(intA[],intMintB[],intN) {intPA = M-1;intPB = N-1;intindex = m + N-1; while(PA >=0&& PB >=0) {if(A[pa] >= B[PB])            {a[index--] = a[pa--]; }Else{a[index--] = b[pb--]; }        } while(Pb >=0) {//Description PA must be 0a[index--] = b[pb--]; }//If PA >= 0, the description [0, PA] has not been judged, because [0, PA] number in a, so do not move}}
Evaluation Results

  Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.

Special Instructions Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47290705"

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Leetcode-Interview algorithm classic-java Implementation" "088-merge Sorted Array (merge sorted array)"

Related Article

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.