Java solution with comment / explanation


  • 0
    S
    public class Solution {
        public void moveZeroes(int[] nums) {
            // use swap to do the operations
            // when encounter a non-zero element, swap it with the first zero
            // ensure during the scan, zero_first is the first zero, and all non-zero elements locates before zero_first
            int zero_first = -1;
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] == 0) {
                    if (zero_first < 0) {
                        zero_first = i;
                    }
                } else { // the element is non-zero
                    if (zero_first < 0) { // 
                        continue;
                    } else {
                        // swap
                        nums[zero_first] = nums[i];
                        nums[i] = 0;
                        // updater zero_first
                        if (nums[zero_first+1] == 0) {
                            zero_first++;
                        } else {
                            zero_first = -1;
                        }
                    }
                }
            }
            return;
        }
    }

Log in to reply
 

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