[LeetCode] [Java] Merge Sorted Array

Source: Internet
Author: User

[LeetCode] [Java] Merge Sorted Array
Question:

 

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1and nums2 are m and n respectively.

Question:

Given two ordered arrays nums1 and nums2, combine the two arrays into an ordered array.

Note:

You can assume that nums1 has enough space (greater than or equal to m + n) to include additional elements from nums2. The numbers of starting elements in nums1and nums2 are m and n.

Algorithm analysis:

Method 1:

The first time AC did not consider too much space complexity, it opened up a new array to contain the merging elements in num1 and nums2, and then overwritten nums1with this new array.

Use two pointers to traverse nums1 and nums2 respectively, and compare the large elements into the new array.

Method 2:

Maintain A pointer for each array, and then compare the value pointed by the pointer. In each iteration, the elements A and B point to are added to the result array, and then index-1, the other does not move. This is because the result of this question is still in A. If you scan it before, it is possible to overwrite the unchecked elements.

AC code:

Method 1:

 

Public class Solution {public void merge (int [] nums1, int m, int [] nums2, int n) {if (n = 0) return; if (m = 0) {for (int I = 0; I
 

Method 2:

 

 

public class Solution {    public void merge(int A[], int m, int B[], int n)     {         while(m > 0 && n > 0)        {            if(A[m-1] > B[n-1])            {                A[m+n-1] = A[m-1];                m--;            }            else            {                A[m+n-1] = B[n-1];                n--;            }        }        while(n > 0){            A[m+n-1] = B[n-1];            n--;        }    }}

 

 

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.