问题描述:
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 temp + n) to hold
additional elements from nums2. The number of elements initialized in nums1 and nums2 are temp and n respectively.
将两个有序数组合并在一起,并依旧保持有序
解题思路:
这个算法是根据Leetcode平台给出的用例改写的,比如nums1:[4,0,0,0,0,0];m=1;nums2:[1,2,2,5,6];n=5。这里我们可以看到nums1空间已经开辟好了,直接把nums2挪到nums1就行。但是我写的比较复杂,模拟插入排序,先把nums2里的数字在nums1中的坐标计算出来,根据坐标进行对应位置插入。
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
//nums1、nums2中一方为空的情况
if(m==0)
{
nums1=nums2;
}
else if(n==0)
{
}
else
{
//比较第一个数字大小,习惯将第一个数字大的vector插入的小的中
if(nums1[0]>=nums2[0])
{
vector<int> t=nums1;
nums1=nums2;
nums2=t;
int temp=n;
n=m;
m=temp;
}
//保存坐标的数组,初始化为-1
int index[n];
for(int i=0; i<n; i++)
{
index[i]=-1;
}
//计算nums2里的数字在nums1中的坐标
int k=0,ix=0;
for(int i=0; i<n; i++)
{
for(int j=k; j<m; j++)
{
if(nums2[i]<=nums1[j+1])
{
index[ix++]=i+j+1;
break;
}
else
{
k=j+1;
}
}
if(nums2[i]>nums1[m-1])
index[ix++]=m+i;
}
//另开辟一个vector初始化
vector<int> nums3;
for(int s3=0; s3<m+n; s3++)
{
nums3.push_back(0);
}
//分别根据坐标将nums2和nums1添加到nums3中,此时已经完成合并
int s2=0;
int s1=0;
for(int s3=0; s3<m+n; s3++)
{
if(s3==index[s2])
{
nums3[s3]=nums2[s2];
s2++;
}
else
{
nums3[s3]=nums1[s1];
s1++;
}
}
nums1.clear();
nums1=nums3;
}
}