Leetcode "Merge Sorted Array" Python implementation

Source: Internet
Author: User

title :

Given sorted integer arrays A and B, merge B into a as one sorted array.

Note:
You could assume that A have enough space (size that's greater or equal to m + n) to the hold additional Eleme NTS from B. The number of elements initialized in A and B is m and nrespectively.

code : OJ Test via runtime:58 ms

1 classSolution:2     #@param a a list of integers3     #@param m An integer, length of A4     #@param B A list of integers5     #@param n An integer, length of B6     #@return Nothing7     defmerge (self, A, M, B, N):8         9Index_total = m + n-1TenIndexa = m-1 OneINDEXB = n-1 A          -          whileIndexa >= 0 andIndexb >=0: -             ifA[indexa] >B[indexb]: theA[index_total] =A[indexa] -Indexa-= 1 -             Else: -A[index_total] =B[indexb] +INDEXB-= 1 -Index_total-= 1 +          A         ifIndexa >=0: at              whileIndexa >=0: -A[index_total] =A[indexa] -Indexa-= 1 -Index_total-= 1 -         Else: -              whileIndexb >=0: inA[index_total] =B[indexb] -INDEXB-= 1 toIndex_total-= 1

Ideas :

Adopt the most basic two-way merger thought. Maintains two pointers for a-B two array.

Here's a trick: to traverse backwards from behind.

This will not create an array of m+n space.

Leetcode "Merge Sorted Array" Python implementation

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.