leetcode第88题合并两个有序数组--双指针

本文讲解了如何在Python中高效地合并两个已排序数组nums1和nums2,通过理解循环结束条件并利用while循环和if-else语句,确保在O(n)时间内完成操作。特别关注了如何在插入元素时调整数组结构,避免不必要的元素移动。
摘要由CSDN通过智能技术生成

注意循环结束条件 

# coding=utf-8
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.class Solution:
class Solution(object):
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: None Do not return anything, modify nums1 in-place instead.
        当需要插入的时候执行m-i+j次
        最后一个空位的索引m+j-1
        m+j-i-2次
        """
        i=j=0
        while j<n:
            if i==m+j:
                nums1[i]=nums2[j]
                i+=1
                j+=1
            else:
                if nums2[j] <= nums1[i]:
                    for offset in range(m+j-i):
                        last_idx=m+j
                        nums1[last_idx-offset]=nums1[last_idx-offset-1]
                    nums1[i]=nums2[j]
                    j+=1
                else:
                    i+=1
        return nums1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值