Move Zeroes — Leetcode
Topic: Array
Difficulty: Easy
Question Number: 283
Problem statement:
Given an integer array nums
, move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Explanation:
The general idea is to scan the array twice.
The first scan uses two pointers: one index pointer to maintain a non-zero subarray( modify the original array ), and the other index to loop through the original array. If the current element being examined is 0, then skip; if it’s not 0, move it to the non-zero subarray.
After the first round, all the non-zero elements should be squeezed to the left part of the original array. So the second round we just add zeros to the empty slots.
Code:
class Solution {
public void moveZeroes(int[] nums) {
int i = 0;
for (final int num : nums)
if (num != 0)
nums[i++] = num;
while (i < nums.length)
nums[i++] = 0;
}
}
Thank you
Oshi Raghav