视频题解
文字题解
从后往前看,在每一个位置上选择A和B中较小的那一个
c++版本代码:
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int a = m-1;
int b = n-1;
for(int i = m+n-1 ; i >= 0 ; i--)//需要填m+n次
{
if(b<0||(a>=0&&A[a]>=B[b]))
//B数组中的数全部用完了就填A数组中的数 a数组中的数没有用完,并且A数组的数大
{
A[i]=A[a];
a--;
}
else
{
A[i]=B[b];
b--;
}
}
}
};
java版本代码:
public class Solution {
public void merge(int A[], int m, int B[], int n) {
int a = m-1;
int b = n-1;
for(int i = m+n-1 ; i >= 0 ; i--)//需要填m+n次
{
if(b<0||(a>=0&&A[a]>=B[b]))
//B数组中的数全部用完了就填A数组中的数 a数组中的数没有用完,并且A数组的数大
{
A[i]=A[a];
a--;
}
else
{
A[i]=B[b];
b--;
}
}
}
}
python版本代码:
class Solution:
def merge(self , A, m, B, n):
a = m-1;
b = n-1;
for i in range(m+n-1,-1,-1):
if b<0 or a>=0 and A[a]>=B[b]:
#B数组中的数全部用完了就填A数组中的数 a数组中的数没有用完,并且A数组的数大
A[i]=A[a]
a=a-1
else:
A[i]=B[b]
b=b-1
京公网安备 11010502036488号