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