forked from Hrudhay-H/Cpp_Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcode_283.cpp
More file actions
37 lines (31 loc) · 1.06 KB
/
Copy pathLeetcode_283.cpp
File metadata and controls
37 lines (31 loc) · 1.06 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
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
// Function to move all zeroes to the end while maintaining the relative order of non-zero elements
void moveZeroes(vector<int>& nums) {
int n = nums.size(); // Get the size of the vector
int j = 0; // Pointer to track the position for non-zero elements
// Iterate through the array
for(int i = 0; i < n; i++) {
if(nums[i] == 0) {
continue; // Skip if the element is zero
}
else {
swap(nums[i], nums[j]); // Swap non-zero element with the element at position j
j++; // Move j to the next position
}
}
}
};
int main() {
Solution s;
vector<int> nums = {0, 1, 0, 3, 12}; // Input vector
s.moveZeroes(nums); // Call function to move zeroes
// Print the modified array
for(int i = 0; i < nums.size(); i++) {
cout << nums[i] << " ";
}
return 0;
}