-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMerge_Sorted_Array.cpp
43 lines (39 loc) · 1.02 KB
/
Merge_Sorted_Array.cpp
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
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
vector<int> sorted; // Temporary vector to store the merged result
int i = 0; // Pointer for nums1
int j = 0; // Pointer for nums2
// Merge elements from nums1 and nums2 until one of them is exhausted
while (i < m && j < n)
{
if (nums1[i] < nums2[j])
{
sorted.push_back(nums1[i]);
i++;
}
else if (nums1[i] > nums2[j])
{
sorted.push_back(nums2[j]);
j++;
}
else
{
sorted.push_back(nums1[i]);
i++;
}
}
// Handle remaining elements from nums1 (if any)
while (i < m) {
sorted.push_back(nums1[i]);
i++;
}
// Handle remaining elements from nums2 (if any)
while (j < n) {
sorted.push_back(nums2[j]);
j++;
}
// Assign the merged result back to nums1
nums1 = sorted;
}
};