【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)
Merge Sorted Array
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
-
The number of elements initialized in nums1 and nums2 are m and n respectively.
-
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
//问题:合并两个有序数组
//方法一:开辟临时数组,通过比较两个有序数组,复制到临时数组中,再把排好序的数组复制回原数组
/*class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
int i=0,j=0,k=0;
vector<int> temp(m+n);
while(i<m&&j<n)
{
temp[k++] = (nums1[i]<nums2[j])? nums1[i++]:nums2[j++];
}
while(i<m)
{
temp[k++] = nums1[i++];
}
while(j<n)
{
temp[k++] = nums2[j++];
}
int size = nums1.size();
if(size >= (m+n))
nums1 = temp;//将排序好元素赋值过去
else
{
nums1.assign(temp.begin(), temp.begin()+size); //仅仅赋值部分元素
cout<<"nums1空间不足!!"<<endl;
}
}
};*/
//方法二:从后往前扫描,依次复制(未开辟额外空间,效率更优)
class Solution
{
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
int i=m-1,j=n-1,k=nums1.size()-1;//从后往前扫描, i,j分别指向有序数组末尾,k指向nums1空间的末尾
while(i>=0 && j>=0)
{
nums1[k--] = (nums1[i] > nums2[j])? nums1[i--]:nums2[j--];
}
while(j >= 0) //将nums2剩余元素复制过去
{
nums1[k--] = nums2[j--];
}
}
};