Merge sorted array

25 年 6 月 29 日 星期日
218 字
2 分钟

problem

Sol 1:

python
class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        nums1[m:] = nums2
        nums1.sort()
        return nums1

copy nums2 then sort

python
class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        i, j = m - 1, n - 1
        p = m + n - 1
        while j >= 0: # ! nums2 还有要合并的元素
            # 如果 p1 < 0,那么走 else 分支,把 nums2 合并到 nums1 中
            if i >= 0 and nums1[i] > nums2[j]: # i >= 0 and
                nums1[p] = nums1[i]
                i -= 1
            else:
                nums1[p] = nums2[j]
                j -= 1
            p -= 1
        return nums1

NOTE:

while j >= 0: Here j is the index of nums2. How to decide the stop conditions is important. Because we must make sure all nums2's elements be moved into nums1. So here we use the index of nums2 as condition.

if i >= 0 and nums1[i] > nums2[j]: if we do not have this i >= 0 then index out of range. Beside if all elements in nums1 has been moved then we must move the nums2's elements. Merge nums2 into nums1.

文章标题:Merge sorted array

文章作者:Sirui Chen

文章链接:https://blog.siruichen.me/posts/88merge_sorted_array[复制]

最后修改时间:


商业转载请联系站长获得授权,非商业转载请注明本文出处及文章链接,您可以自由地在任何媒体以任何形式复制和分发作品,也可以修改和创作,但是分发衍生作品时必须采用相同的许可协议。
本文采用CC BY-NC-SA 4.0进行许可。