classSolution: defmerge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ i = 0 for num in nums2: # find pos in nums1 while i <= m: if i == m: # end, append nums1.insert(i, num) m += 1 del nums1[-1] break if nums1[i] < num: i += 1 continue # nums1[i] >= n, insert number nums1.insert(i, num) m += 1 del nums1[-1] break
However, this is not the fastest because every time we need to push back the array to insert, also, del in Python is O(n) operation. How can we improve? We can utilize the empty space left in nums1 array and compare from the back. Also, this solution is more generalized because the previous one is only for 2 array, but this works for multiple arrays.