题目:
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m andn respectively.
思路:维护三个index,分别对应数组A,数组B,和结果数组;通过判断,给A赋值;
Attention:数组元素要从后往前遍历,否则会覆盖A的原始数值。
AC Code:
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
//合并两个有序数组,升序排列
//思路:维护三个index
//Attention: 数组元素要从后往前遍历,否则会覆盖A的原始数值。
if(A == NULL)
{
A = B;
return;
}
int indA = m - 1;
int indB = n - 1;
int len = m + n -1;
for(;len >= 0;)
{
if(indA >= 0 && ( indB < 0 || A[indA] >= B[indB]))
A[len--] = A[indA--];
else
A[len--] = B[indB--];
}
return;
}
};
Error Code:
复杂思路:数组类似于顺序线性表。依次取出B的元素,遍历A的元素,插入到合适的位置。!!!
代码有问题:
Submission Result: Wrong Answer
Input: | [], [1] |
Output: | [151539712] |
Expected: | [1] |
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
//合并两个有序数组,并且A有充足的位置。
//思路:数组类似于顺序线性表。依次取出B的元素,遍历A的元素,插入到合适的位置。
//注意要移动A中插入位置后的元素
if(m == 0)
{
A = B;
return;
}
int i = n-1;
int j = m-1;
while(i >= 0)
{
int k = 0; // 插入位置
//假设A,B按升序排列
while(j >= 0)
{
if(B[i] >= A[j])
{
k = j + 1;
break;
}
j--;
}
j = (m - 1) + (i - n + 1);
//插入B[i],并且移动A[j]后的元素。如果k不是最后一个元素
if(k <= j)
{
for(int mv = j -1; mv >= k; mv--)
{
A[mv+1] = A[mv];
}
}
//插入元素B[i]
A[k] = B[i];
j++;
i--;
}
return;
}
};