Suppose we have two sorted arrays A and B. We have to merge them and form only one sorted array C. The size of lists may different.
For an example, suppose A = [1,2,4,7] and B = [1,3,4,5,6,8], then merged list C will be [1,1,2,3,4,4,5,6,7,8]
To solve this, follow these steps −
The shift method will work like below −
Let us see the implementation to get better understanding
class Solution(object): def merge(self, nums1, m, nums2, n): i = 0 j = 0 end = len(nums1)-1 while end>=0 and not nums1[end]: end-=1 while j<len(nums2) : if i>end and not nums1[i]: nums1[i] = nums2[j] j+=1 elif nums1[i]>nums2[j]: self.shift(nums1,i) nums1[i] = nums2[j] end+=1 j+=1 i+=1 return nums1 def shift(self,num,i): j = len(num)-1 while not num[j]: j-=1 while j>=i: num[j+1] = num[j] j-=1 ob = Solution() print(ob.merge([1,2,3,0,0,0],3,[2,5,6],3))
[1,2,3,0,0,0] [2,5,6]
[1, 2, 2, 3, 5, 6]