Python write from nums1[m + n] - 1 to nums1[0]


  • 0

    Initially, I tried to write the nums1 from front to the end, but this will scratch the undetermined element of nums1. Then, I have to write the nums1 from m + n - 1 place to 0:
    idx, i1, i2 stands for the next place to be written, end of nums1, end of nums2, if idx < 0 then it means all be written, if i2 < 0, because nums1 is sorted, also means things get set.

    class Solution(object):
        def merge(self, nums1, m, nums2, n):
            idx, i1, i2 = m + n - 1, m - 1, n - 1
            while idx >= 0 and i2 >= 0:
                if i1 < 0:
                    nums1[idx] = nums2[i2]
                    i2 -= 1
                    idx -= 1
                else:
                    if nums1[i1] > nums2[i2]:
                        nums1[idx] = nums1[i1]
                        i1 -= 1
                    else:
                        nums1[idx] = nums2[i2]
                        i2 -= 1
                    idx -= 1
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.