88. Merge Sorted Array
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 m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
问题描述:将两个有序数组合并成一个有序数组。
思路:创建第三个数组,将其它两个数组有序的插入第三个数组中。然后根据需求变化。
代码如下:
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
vector<int> result;
int i= 0;
int j=0;
while( (i < m) && (j < n))
{
if(nums1[i] <= nums2[j])
{
result.push_back(nums1[i]);
i++;
}
else
{
result.push_back(nums2[j]);
j++;
}
}
if(i < m)
{
for(;i < m; i++ )
{
result.push_back(nums1[i]);
}
}
if(j < n)
{
for(;j < n; j++)
{
result.push_back(nums2[j]);
}
}
swap(result,nums1);
}
};
2016-08-05 23:36:14
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。