Mobile zero

Given an array nums, write a function to move all zeros to the end of the array while preserving the relative order of the non-zero elements.

Examples can be found on the LeetCode website.

Source: LeetCode link: leetcode-cn.com/problems/mo… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Solution 1: array traversal

First, we declare a variable theLastNotZeroPos to record the last non-zero position. Then we iterate through nums from the back. If the element in the array is equal to zero, we do the following:

  • If the current position is equal to theLastNotZeroPos, then theLastNotZeroPos is subtracted by one, continuing through the next element;
  • If the current position is not equal to theLastNotZeroPos, move all elements from the last bit of the current position to theLastNotZeroPos one bit ahead, then change theLastNotZeroPos to 0, and subtract theLastNotZeroPos by one. And then the next element.

After traversal is completed, it is the result after moving.

public class LeetCode_283 {
    public static void moveZeroes(int[] nums) {
        // The last non-zero position
        int theLastNotZeroPos = nums.length - 1;
        for (int i = nums.length - 1; i >= 0; i--) {
            if (nums[i] == 0) {
                if(i ! = theLastNotZeroPos) {for (int j = i; j < theLastNotZeroPos; j++) {
                        nums[j] = nums[j + 1];
                    }
                    nums[theLastNotZeroPos] = 0; } theLastNotZeroPos--; }}}public static void main(String[] args) {
        int[] nums = new int[] {0.1.0.3.12};
        System.out.println("----- before moving -----");
        for (int num : nums) {
            System.out.print(num + "");
        }
        System.out.println();
        moveZeroes(nums);
        System.out.println("----- after moving -----");
        for (int num : nums) {
            System.out.print(num + ""); }}}Copy the code

The uncertainty of life is the source of our hope.