-
Notifications
You must be signed in to change notification settings - Fork 13
/
CS_22_MoveZeroesToEnd.cpp
61 lines (58 loc) · 1.23 KB
/
CS_22_MoveZeroesToEnd.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <bits/stdc++.h>
using namespace std;
vector<int> moveZeros(int n, vector<int> a)
{
// Brute: TC: O(2n), SC: O(n)
// vector<int> temp;
// for (int i = 0; i < n; i++) {
// if (a[i] != 0)
// temp.push_back(a[i]);
// }
// int zerosToBeAdded = n - temp.size();
// for (int i = 0; i < zerosToBeAdded; i++) {
// temp.push_back(0);
// }
// return temp;
// Two pointers
// Optimal: TC: O(n), SC: O(1)
int j = -1;
for (int i = 0; i < n; i++)
{
if (a[i] == 0)
{
j = i;
break;
}
}
if (j == -1)
return a;
for (int i = j + 1; i < n; i++)
{
if (a[i] != 0)
{
swap(a[j], a[i]);
j++;
}
}
return a;
}
int main()
{
cout << "Enter the number of elements in the array: ";
int n;
cin >> n;
cout << "Enter the elements of the array: ";
vector<int> a(n);
for (int i = 0; i < n; ++i)
{
cin >> a[i];
}
vector<int> ans = moveZeros(n, a);
cout << "The array after moving all the zeros to the end is: ";
for (int i = 0; i < n; ++i)
{
cout << ans[i] << " ";
}
cout << endl;
return 0;
}