Mergesortedarray, merging two ordered arrays

Source: Internet
Author: User

Description of the problem: assume that nums1 have enough space (size is greater or equal to m + n) to Hol D additional elements from Nums2. The number of elements initialized in nums1 and nums2 is m and n respectively.

Algorithm Analysis: Merge two arrays, but the merged array is the original array 1, cannot create new space, assuming that the array 1 has enough space, from backward to forward, to avoid overwriting problems. Similar problems include the merging of two ordered lists, linked lists and arrays.

From backward to forward comparison, you will not encounter problems with overrides public class Mergesortedarray{public void merge (int[] nums1, int m, int[] nums2, int n) {int i = m-1, j = N-1;int z = m+n-1;        while (i >= 0 && J >= 0)        {        if (Nums1[i] > Nums2[j])        {        nums1[z--] = nums1[i--];        }        else        {        nums1[z--] = nums2[j--];         }        }        if (I < 0)        {for        (int k = j; k >= 0; k--)        {        nums1[z--] = nums2[k]        ;    }}}

Merge two ordered linked lists:

public class Solution {public    ListNode mergetwolists (listnode L1, ListNode L2) {        ListNode dumy = new ListNode (0);        ListNode head = dumy;        while (L1 = null && L2! = null)        {            if (L1.val < L2.val)            {                dumy.next = L1;                L1 = L1.next;            }            else            {                dumy.next = L2;                L2 = L2.next;            }            Dumy = Dumy.next;        }        if (L1 = = null)        {            dumy.next = L2;        }        if (L2 = = null)        {            dumy.next = L1;        }        return head.next;}    }

Mergesortedarray, merging two ordered arrays

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.