题目描述
给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。
请你 合并 nums2 到 nums1 中,使合并后的数组同样按 非递减顺序 排列。
注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1 中。为了应对这种情况,nums1 的初始长度为 m + n,其中前 m 个元素表示应合并的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n 。
思路一:创建临时数组
- 使用两个指针,遍历
nums1
与nums2
,依次将最小值填入新创建的数组newarr
- 需要额外空间存储新创建的数组,空间复杂度为 O ( m + n ) O(m+n) O(m+n)
class Solution {
public:
int trap(vector<int>& height) {
const int len=30000;
int leftmax[len],rightmax[len],res=0;
int left=height[0],right=height[height.size()-1];
for(int i=0;i<height.size();i++){
//left
leftmax[i]=max(height[i],left);
left=leftmax[i];
//right
rightmax[height.size()-1-i]=max(height[height.size()-1-i],right);
right=rightmax[height.size()-1-i];
}
for(int i=0;i<height.size();i++){
res+=min(leftmax[i],rightmax[i])-height[i];
}
return res;
}
};
思路二:从nums1末尾开始合并
- 省去存储m+n个元素额外空间
- 需要注意终止条件
- 时间复杂度为 O ( m + n ) O(m+n) O(m+n)
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
if(n==0){
return;
}
if(m==0){
nums1=nums2;
return;
}
int pt1=m-1,pt2=n-1;
for(int i=m+n-1;i>=0;i--){
if(pt1>=0&&pt2>=0){
nums1[i]=max(nums1[pt1],nums2[pt2]);
if(nums1[pt1]>=nums2[pt2]){
pt1--;
}else{
pt2--;
}
}else if(pt1<0){
while(pt2>=0){
nums1[i]=nums2[pt2];
pt2--;
i--;
}
}else{
while(pt1>=0){
nums1[i]=nums1[pt1];
pt1--;
i--;
}
}
}
}
};
思路三:先合并再排序
- 将
nums2
存进nums1
,再用sort()
进行升序排序 - 时间复杂度为 O ( n log n ) O(n\log n) O(nlogn)
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
for(int i=0;i<n;i++){
nums1[m+i]=nums2[i];
}
sort(nums1.begin(),nums1.end());
}
};