Merge Sorted Array

题目详情:https://leetcode.com/problems/merge-sorted-array/#/description
我感觉这道题没什么好说的,简单粗暴。本题不能扩大nums1的容量,只能在题目要求的空间内操作,所以像插入,添加都是会提交错误的!

#-*- coding: UTF-8 -*-
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: void Do not return anything, modify nums1 in-place instead.
        """
        i=j=0 #i指向nums1,j指向nums2
        length=0
        while  i<m and j<n:
            if nums1[i] >= nums2[j]:
                t=m-1
                while t >= i: #nums1中的元素往后移,一遍腾出位置,给新元素
                    nums1[t+1]=nums1[t]
                    t=t-1
                nums1[i]=nums2[j] #添加新元素
                j=j+1
                i=i+1 #i 加1,因为添加了nums2中的一个新元素,添加到了nums1[i]位置
                m=m+1 #  m加1,因为有添加进一个新的元素
            else: #nums1[i] < nums2[j]
                i=i+1 #较小的元素已经在nums1中了,只需要将nums1中下标加1即可
            length=length+1
        if i < m: #此时什么也不用做,因为以合并到nums1中去
            pass #剩下的数就在nums1中
        if j < n:
            while j<n:
                nums1[length]=nums2[j]
                j=j+1
                length=length+1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值