Move Zeroes
Given an integer array nums0
Note that you must do this in-place without making a copy of the array.
Example 1
Output: [1,3,12,0,0]
Example 2
Output: [0]
Constraints:
1 <= nums.length <= 104-231 <= nums[i] <= 231 - 1
Follow up: Could you minimize the total number of operations done?
Solution 1 - Move non-zero elements to the beginning, fill remaining with 0's
In this approach, we will move all non-zero elements to the beginning of the array, then fill remaining with 0's,
say if there are nmmm-n
For example, consider input array nums = [0,1,0,3,12][1,3,12,↑3,12]5 -3 =2[1,3,12,0,0]
Implementation steps:
-
We will create a variable
, to keep track index where to move non-zero elements.nonZeroIndex =0 -
Then, loop through elements of input array
and if it's a non-zero element update thenums array at indexnums , and incrementnonZeroIndex .nonZeroIndex -
At the end,
will be at a position where all non-zero elements are moved to left side of array, now we will fill reamining elements fromnonZeroIndex until end of array with 0's.nonZeroIndex
import java.util.Arrays;
public class MoveZeroes {
static void moveZeroes(int[] nums) {
int nonZeroIndex = 0;
for(int i=0; i<nums.length; i++) {
if(nums[i] != 0) {
nums[nonZeroIndex] = nums[i];
nonZeroIndex++;
}
}
// fill all remaining elements with 0's from where nonZeroIndex ended till end of array
while(nonZeroIndex<nums.length){
nums[nonZeroIndex] = 0;
nonZeroIndex++;
}
}
public static void main(String[] args) {
int[] nums = {0,1,0,3,12};
moveZeroes(nums);
System.out.println(Arrays.toString(nums));
nums = new int[]{0};
moveZeroes(nums);
System.out.println(Arrays.toString(nums));
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n) time where nnums
Space complexity: O(1).
Above implementations source code can be found at