Move Zeroes
Question:
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.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
Difficulty: Easy
Similar Problem: Remove Element
Link: https://leetcode.com/problems/move-zeroes/
Solution: Scan the arrays and put the non-zero number in the front of array, then do nothing on zero.
Step-1: Build two pointers named: zeroPointer and scanner. zeroPointer is used for point the position that we swap next time. scanner is used for scan the each value of the array.
Step-2: Create a while loop and begin to scan the array. Obviously, the exit condition is when the scanner reach the end of the array. In the loop, we will have a if condition to check the value is zero or not. If it's zero, just do nothing and move scanner to the next. If it's not zero, swap the number in current position to zeroPotiner. And then move both scanner and zeroPointer to the next.
Code:
public class Solution {
public void moveZeroes(int[] nums) {
int zeroPointer = 0;
int scanner = 0;
while(scanner < nums.length){
if(nums[scanner] != 0){
int t = nums[scanner];
nums[scanner] = nums[zeroPointer];
nums[zeroPointer] = t;
zeroPointer++;
}
scanner++;
}
}
}