您的位置:首页 > 其它

《leetCode》:Merge Sorted Array

2015-12-24 21:04 447 查看

题目

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.


题目大意:对两个已排序的数组进行合并。

此题比较简单,直接从两个数组从后往前遍历,然后将大的进行存储在nums1的尾端即可。

//思路:从后往前遍历
void merge(int* nums1, int m, int* nums2, int n) {
if(n<1){
return ;
}
if(m<1){//第一个数组元素为空
for(int i=0;i<n;i++){
nums1[i]=nums2[i];
}
return ;
}
int index=m+n-1;
int p1=m-1;
int p2=n-1;
while(p1>=0&&p2>=0){
if(nums1[p1]>=nums2[p2]){
nums1[index--]=nums1[p1];
p1--;
}
else if(nums1[p1]<nums2[p2]){
nums1[index--]=nums2[p2];
p2--;
}
}
//如果是p2<0退出,则就已完成,如果是p1<0退出,则还需要将p2个元素拷贝要nums1中
if(p1<0&&p2>=0){
for(int i=0;i<=p2;i++){
nums1[i]=nums2[i];
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: