Article Directory
foreword
"Maybe you are not brilliant or even a little dull, but you are a star and romantic."
The content of this chapter is the analysis of part of the method of Rikko's daily random question
提示:以下是本篇文章正文内容,下面案例可供参考
88. Merge two sorted arrays
You are given two integer arrays nums1 and nums2 arranged in non-decreasing order, and two integers m and n denoting the number of elements in nums1 and nums2 respectively.
Please merge nums2 into nums1 so that the merged array is also arranged in non-decreasing order.
Note: Ultimately, the merged array should not be returned by the function, but stored in the array nums1. To cope with this situation, the initial length of nums1 is m + n, where the first m elements represent elements that should be merged, and the last n elements are 0 and should be ignored. nums2 has length n.
Link:
88. Merge two sorted arrays link
Method 1: Three pointers (back insertion)
1.2 Code:
void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n)
{
int end1=m-1;
int end2=n-1;
int i=m+n-1;
while(end1>=0&&end2>=0)
{
if(nums1[end1]>nums2[end2])
{
nums1[i--]=nums1[end1--];
}
else
{
nums1[i--]=nums2[end2--];
}
}
while(end2>=0)
{
nums1[i--]=nums2[end2--];
}
return nums1;
}
1.2 Flowchart:
It's not all finished, only a part of it
Method 2: Open up a new space
2.1 Code:
void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n)
{
int p1=0;
int p2=0;
int tmp=0;
int* end=(int*)malloc(sizeof(int)*(n+m));
while(p1<m||p2<n)
{
if(p1==m)
{
tmp=nums2[p2++];
}
else if(p2==n)
{
tmp=nums1[p1++];
}
else if(nums1[p1]>nums2[p2])
{
tmp=nums2[p2++];
}
else
{
tmp=nums1[p1++];
}
end[p1+p2-1]=tmp;
}
for(int i=0;i<m+n;i++)
{
nums1[i]=end[i];
}
return nums1;
free(end);
end=NULL;
}
2.2 Flowchart:
2.3 Note:
- Consider the case where p1 is a single element or an empty element
- Consider the case where p2 is a single element or an empty element
- It should be noted that p1<m||p2<n can exit the loop if neither of them match
Summarize
Ending, this is the end of today's Likou daily question content. If you want to know more in the future, please follow me. There are many methods that have not been written. I hope you guys can add them~