Merge -sorted-array
Title description
Given two ordered arrays of integers A and B, please merge array B into array A to become an ordered array.
Note: It
can be assumed that the A array has enough space to store the elements of the B array, A and B The initial number of elements are m and n
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 to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
Problem-solving ideas
- Three pointers, start from the m+n-1 position of A and merge sequentially, that is, merge A and B from large to small
- The pointers pa and pb are used to traverse the A and B arrays from back to front. The initial values are m-1 and n-1 respectively, which represent the right subscripts pointing to the elements of A and B.
- The pointer index is used to point to the right subscript of the merged area. The initial value is m+n-1, which means it points to the last position of the merged area.
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
//分别用于遍历数组A和B,初始指向右下标
int pa(m - 1), pb(n - 1);
//用于记录合并后数组的右下标
int index(m + n - 1);
while(pa >= 0 && pb >= 0) {
if(A[pa] > B[pb]) {
A[index --] = A[pa --];
} else {
A[index --] = B[pb --];
}
}
while(pb >= 0) A[index --] = B[pb --];
}
};