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.
Hide Tags: Array, Two Pointers
题目:合并两个已排好序的数组,要求合并后同样保持排好序
思路:采用两个指针分别从两个数组开头向后移,并且比较。提前需要分配一个能存下两个数组的临时数组。
void merge(int* nums1, int m, int* nums2, int n) {
int lpos = 0, rpos = 0, tmpos = 0;
int* tem = (int*)malloc(sizeof(int)*(m+n));
while(lpos < m && rpos < n)
{
if(nums1[lpos] < nums2[rpos])
tem[tmpos++] = nums1[lpos++];
else
tem[tmpos++] = nums2[rpos++];
}
while(lpos < m)
{
tem[tmpos++] = nums1[lpos++];
}
while(rpos < n)
{
tem[tmpos++] = nums2[rpos++];
}
int i = 0;
for(i=0;i<m+n;i++)
{
nums1[i] = tem[i];
}
free(tem);
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/xiabodan/article/details/46771777