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.
问题描述:将两个有序数组合并成一个有序数组。
思路:创建第三个数组,将其它两个数组有序的插入第三个数组中。然后根据需求变化。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
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);
}
};
|
本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1834908