fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<int> moveZeros(int n, vector<int> a) {
  5. int j = -1;
  6. //place the pointer j:
  7. for (int i = 0; i < n; i++) {
  8. if (a[i] == 0) {
  9. j = i;
  10. break;
  11. }
  12. }
  13.  
  14. //no non-zero elements:
  15. if (j == -1) return a;
  16.  
  17. //Move the pointers i and j
  18. //and swap accordingly:
  19. for (int i = j + 1; i < n; i++) {
  20. if (a[i] != 0) {
  21. swap(a[i], a[j]);
  22. j++;
  23. }
  24. }
  25. return a;
  26. }
  27.  
  28.  
  29. int main()
  30. {
  31. vector<int> arr = {1, 0, 2, 3, 2, 0, 0, 4, 5, 1};
  32. int n = 10;
  33. vector<int> ans = moveZeros(n, arr);
  34. for (auto &it : ans) {
  35. cout << it << " ";
  36. }
  37. cout << '\n';
  38. return 0;
  39. }
  40.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
1 2 3 2 4 5 1 0 0 0