-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path88.merge-sorted-array.cpp
More file actions
57 lines (56 loc) · 1.17 KB
/
88.merge-sorted-array.cpp
File metadata and controls
57 lines (56 loc) · 1.17 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
* @lc app=leetcode id=88 lang=cpp
*
* [88] Merge Sorted Array
*/
// @lc code=start
int MAX = 1000000000 + 1;
class Solution
{
public:
void merge(vector<int> &nums1, int m, vector<int> &nums2, int n)
{
if (m == 0)
{
for (int i = 0; i < n; i++)
{
nums1[i] = nums2[i];
}
return;
}
if (n == 0)
{
return;
}
// move element to nums1 bottom
int tail = nums1.size() - 1;
int last = m - 1;
while (last >= 0)
{
nums1[tail] = nums1[last];
nums1[last] = 0;
tail--;
last--;
}
int p1 = tail + 1;
int p2 = 0;
int p = 0;
while (p1 < nums1.size() || p2 < nums2.size())
{
int n1 = p1 < nums1.size() ? nums1[p1] : MAX;
int n2 = p2 < nums2.size() ? nums2[p2] : MAX;
if (n1 < n2)
{
nums1[p] = n1;
p1++;
}
else
{
nums1[p] = n2;
p2++;
}
p++;
}
}
};
// @lc code=end