# 8ms simple C solution

• ``````void moveZeroes(int* nums, int numsSize) {
int totalZeros = 0;

for(int i = 0; i < numsSize; i++) {
if(nums[i] == 0) {
totalZeros++;
}
else {
nums[i - totalZeros] = nums[i];
}
}

for(int i = (numsSize - totalZeros); i < numsSize; i++) {
nums[i] = 0;
}
}``````

• very clever
I suppose it can minimize the shift of non-zero elements

• good. but i use the same method, it costs 20ms

• @joe297 The same language?

• Nice! I came up with something very similar, but instead of doing a second loop I used a conditional assignment near the end of the first loop. It seems to run ~2ms faster this way (6ms was my result with 21 test cases):

``````void moveZeroes(int* nums, int numsSize)
{
int i, shift = 0;

for (i = 0; i < numsSize; i++) {
if (nums[i] == 0) {
shift++;
continue;
}

nums[i - shift] = nums[i];
if (shift)
nums[i] = 0;
}
}
``````

• similar ,6ms
void moveZeroes(int* nums, int numsSize) {
int idx = 0;

``````for(int i = 0; i < numsSize; i++) {
if(nums[i] != 0) {
nums[idx++] = nums[i];
}
}

for(int i = idx; i < numsSize; i++) {
nums[i] = 0;
}
``````

}

• @joe297 I did the exactly same thing in C++ and it costs me 16ms.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.