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