-
Notifications
You must be signed in to change notification settings - Fork 0
/
9_merge2Array.cpp
42 lines (36 loc) · 1002 Bytes
/
9_merge2Array.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
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
//Swap elements
int left = m - 1;
int right = 0;
//Left ptr for nums1 end, and right for nums2 start
//Compare if left > right if yes then swap, else end
while (left >= 0 && right < n){
if (nums1[left] > nums2[right]){
swap(nums1[left], nums2[right]);
left--,right++;
}else{
break;
}
}
//Sorting the array after swapping values
sort(nums1.begin(), nums1.begin()+ m);
sort(nums2.begin(), nums2.end());
//Putting the values of the right array in left
int p1 = m;
for (int i = 0; i < nums2.size(); i++){
nums1[p1++] = nums2[i];
}
for (int y: nums1){
cout << y << " ";
}
}
};
int main()
{
return 0;
}