https://leetcode.com/problems/merge-sorted-array/

https://leetcode.com/problems/merge-sorted-array/

这道题有一个很奇怪的问题 看了discuss之后明白了 

A B数组的长度其实是不确定的 所以len(A)是不能用的

这也是为什么会给出m,n作为长度 

大家的解释是 A的实际长度长于m 这是为了最后mergeB留的空间 

但是有一个testcase 

input[],[1]

out[0]

expected[1]

为什么输出0我也不是很清楚 

网友的解释:

Finally, I got the answer. Although they are given A as [], but actually, the A is filled with 0 to occupy enough space for B. That means you can never use len(A) or things similar. In your case your A may result in "01," but system only show the first bit "0", so you cannot pass it. My codes below has similar problem when I use len(A),

所以这道题我用的是两个指针 比较

B小就把B放在A前面 B大就判断 如果A已经结束了就全部插在后面 如果A没结束 就把A的指针后移 再次比较

特殊情况就是A为空 就依次复制B B为空 直接返回A


class Solution:
    # @param A  a list of integers
    # @param m  an integer, length of A
    # @param B  a list of integers
    # @param n  an integer, length of B
    # @return nothing(void)
    def merge(self, A, m, B, n):
        x=0
        y=0
        if m!=0 and n!=0:
            while y<n:
                if B[y]<=A[x]:
                    A.insert(x,B[y])
                    y=y+1
                    x=x+1
                    m=m+1
                else:
                    if x!=m-1:
                        x=x+1
                    else:
                        A.insert(x+1,B[y])
                        x=x+1
                        y=y+1
                        m=m+1
        elif m==0 and n!=0:
            while y<n:
                A.insert(x,B[y])
                x=x+1
                y=y+1
        else:
            A=A
                    
                




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值