Merge Sorted Array
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 and n respectively.
题意:给定两个有序数组A、B,把B数组的类容合并到A中。
notes:你可以假设A数组已经足够大,可以容纳A、B合并后的元素,对两个数组的初始化数组大小为m,n。
解题思路:有序数组,则A,B数组是排好序了的,把B中的元素插入A中,需要判断B中元素在A数组中的放置位置,需要对A数组进行折半查找,当A[i]<=B[j]<=A[i+1],则就可以把B[j]元素插入A[i],A[i+1]之间。
难点:折半查找,数组移动(元素插入)。
C语言实现代码,比较累赘:
/**
* 解题思路:B有序数组合并到A有序数组中,利用折半查找方法,查看B[i]元素在A中的那个位置,并把key元素插入A的相应位置中
* 注意在A数中的末尾插入或者开头插入,小于某元素时在元素前插入,大于某元素时在元素后插入
*
*/
int compare(int key, int *a, int n){
int low, high, mid;
low = 0;
high = n-1;
mid = 0;
while(low <= high){
mid = (low + high)/2;
if(key > a[mid]){
low = mid + 1;
}else if(key < a[mid]){
high = mid - 1;
}else{
return mid;
}
}
if(mid > high){//当key值小于A中的最小值时,需要把key插入A中的最前面
return mid-1;
}
return mid;
}
void insert(int key, int n, int *a,int mid){
int i;
for(i = n-2;i > mid;i--){
a[i+1] = a[i];
}
a[mid+1] = key;
}
void merge(int A[], int m, int B[], int n) {
int i,j,temp;
if(A == NULL && B == NULL){
return;
}
if(m == 0){
for(i = 0; i < n; i++){
A[i] = B[i];
}
return;
}
for(i = 0; i < n; i++){
temp = compare(B[i], A, m);
m++;
insert(B[i],m, A, temp);
}
}
该博客介绍了如何使用C语言解决LeetCode中的'Merge Sorted Array'问题。博主详细解释了题意,指出解题关键在于有序数组的特性,以及如何通过折半查找确定B数组元素在A数组中的合适位置。文章还强调了难点在于执行高效的数组元素移动。
614

被折叠的 条评论
为什么被折叠?



