您的位置:首页 > 其它

LeetCode 88. Merge Sorted Array

2016-05-17 15:49 429 查看
88、 Merge Sorted Array

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.

对两个已经排好序的数组1,2进行合并,并且要合并到1中,合并之后的数组也是排好序的。

一开始我想的是利用vector的insert函数进行插入,但写完之后出现来bug,可能是我对insert函数的理解不太对吧。后来用的是从后到前的顺序进行合并的,这样就可以避免插入数据的时候,后面的所有数据要往后移的操作。

AC代码:

void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int index = m+n-1;
int aIndex = m-1;
int bIndex = n-1;
while(aIndex>=0 && bIndex>=0){
if(nums1[aIndex]>nums2[bIndex]){
nums1[index] = nums1[aIndex];
index--;
aIndex--;
}else{
nums1[index] = nums2[bIndex];
index--;
bIndex--;
}
}
while(aIndex>=0){
nums1[index] = nums1[aIndex];
index--;
aIndex--;
}

while(bIndex>=0){
nums1[index] = nums2[bIndex];
index--;
bIndex--;
}
}


如代码所示,从后往前比较,大的放后面,并且把相应的下标前移一位。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: