Move Zeroes LeetCode | Move Zeroes to End of Array | Programming Tutorials

preview_player
Показать описание
Move zeroes to end of array without using extra memory Java code. Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

In this tutorial, i have explained how to push all the zeros that are present to the end of the array efficiently.

For example :

Example 1:

Input: {1, 0, 2, 3, 0, 0, 0, 2}
Output: {1, 2, 3, 2, 0, 0, 0, 0}

In this output, We moved all zeroes to the end, while maintaining
the relative order of all non-zero elements.


Example 2:

Input : {0, 6, 0, 9, 11}
Output: {6, 9, 11, 0, 0}

NOTE:
We have solve this problem in-place without making a copy of the array.

This problem is the day 4 challenge of LeetCode 30 day challenge.

Рекомендации по теме
Комментарии
Автор

Thanks sir, you made it really easy to understand.

minhadrizwan
Автор

Nice explanation, Keep posting and keep helping !!

_jitendrakumarr
Автор

I'm having a problem with my code:
whenever I try this method, it just makes a recursive loop. Can you see anything wrong with it?

int k = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] != 0) {

array[k + 1] = array[i];
}
}
while (k < array.length) {
array[k + 1] = 0;

}

mallow