您的位置:首页 > 其它

Facebook Phone Interview -- Move Zeros to Right (Easy)

2016-03-23 07:13 288 查看
March 22th, 2016.

Move Zeros to the right end but keep the order of non-zero numbers.

#include <stdio.h>
#inlcude <iostream>
#include <vector>
using namespace std;

// move Zeros to the right end of the array.
// classical two pointers problem.
void moveZeroToRight(vector<int>& array) {
if(array.size() <= 1) return; // if the array only has 0-1 values, no need to sort.
int left = 0; // one pointer to remember the left copy.
int i = 0; // one pointer to loop the array.
while(i < array.size()) {
if(array[i] != 0) {
array[left++] = array[i++]; // if it is not zero, copy it to the left end.
} else {
i++;  // otherwise, i pointer keeps on moving.
}
}
// copy all non-zeros to the left now. But we need to remember to set the left values to 0.
while(left < array.size()) {
array[left++] = 0;
}
}

// the following is for test purpose.
void printArray(vector<int> array) {
for(int i = 0; i < array.size(); ++i) {
printf("%d\n", array[i]);
}
}

int main(void) {
vector<int> array;
array.push_back(0); array.push_back(1);
moveZeroToRight(array);
printArray(array);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: