Skip to content

Instantly share code, notes, and snippets.

@sturgle
Last active January 1, 2016 14:49
Show Gist options
  • Save sturgle/8160146 to your computer and use it in GitHub Desktop.
Save sturgle/8160146 to your computer and use it in GitHub Desktop.
/*
http://www.careercup.com/question?id=12986664
Push all the zero's of a given array to the end of the array. In place only. Ex 1,2,0,4,0,0,8 becomes 1,2,4,8,0,0,0
*/
#include <vector>
#include <iostream>
using namespace std;
void putZeroToEnd(vector<int> &vec) {
// i for next non-zero num index
// j for normal move forward index
int i = 0;
int j = 0;
while (j < vec.size()) {
if (vec[j] == 0) {
j++;
}
else {
vec[i] = vec[j];
i++;
j++;
}
}
while (i < vec.size()) {
vec[i] = 0;
i++;
}
}
int main() {
vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(0);
vec.push_back(4);
vec.push_back(0);
vec.push_back(0);
vec.push_back(8);
putZeroToEnd(vec);
for (int i = 0; i < vec.size(); i++) {
cout << vec[i] << " ";
}
cout << endl;
system("pause");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment