[Oracle] LeetCode 88 Merge Sorted Array 双指针
You are given two integer arrays nums1
and nums2
, sorted in non-decreasing order, and two integers m
and n
, representing the number of elements in nums1
and nums2
respectively.
Merge nums1
and nums2
into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1
. To accommodate this, nums1
has a length of m + n
, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2
has a length of n
.
Solution
点击查看代码
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
if(n==0)return;
else if(m==0){
for(int i=0;i<n;i++)nums1[i]=nums2[i];
return;
}
else{
vector<int> tmp;
for(int i=0;i<m;i++)tmp.push_back(nums1[i]);
int p1=0,p2=0;
int cnt=0;
while(p1<m && p2<n){
if(tmp[p1]<nums2[p2]){
nums1[cnt]=tmp[p1];p1++;cnt++;
}
else{
nums1[cnt]=nums2[p2];p2++;cnt++;
}
}
if(p2<n){
for(int i=p2;i<n;i++){
nums1[cnt]=nums2[i];cnt++;
}
return;
}
else{
for(int i=p1;i<m;i++){
nums1[cnt]=tmp[i];cnt++;
}
return;
}
}
}
};