[Leetcode] Merge Sorted Array

Source: Internet
Author: User

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

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.

This problem seems to have nothing to say. relatively simple.

This question is the simplest from the end. Because this is equivalent to inserting a sorted array into another sorted array with extra space.

However, be aware of the special case, the code is written when there is extra space in the sorted array has been sorted after the completion of another array of the element of the sort.

The code is as follows. ~

public class Solution {public    void merge (int[] nums1, int m, int[] nums2, int n) {        int a=m-1;        int b=n-1;        int start=m+n-1;        while (a>=0&&b>=0) {            if (Nums1[a]>nums2[b]) {                nums1[start--]=nums1[a--];            } else{                nums1[start--]=nums2[b--];            }        }        if (a<=0) {            while (b>=0) {                nums1[start--]=nums2[b--];            }        }    }

[Leetcode] 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.