2
头图

Move zero

Title description: Given an array nums , write a function to move all 0 to the end of the array while maintaining the relative order of non-zero elements.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/move-zeroes/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution one: array traversal

First, declare a variable theLastNotZeroPos to record the last non-zero position, and then traverse the array nums from back to front. If the elements of the array are equal to 0, the following processing is required:

  • If the current position is equal to theLastNotZeroPos, then decrease theLastNotZeroPos by one and continue to traverse the next element;
  • If the current position is not equal to theLastNotZeroPos, move all the elements from the last position to theLastNotZeroPos forward by one position, and then change the element at theLastNotZeroPos position to 0, and reduce theLastNotZeroPos by one, and then process the next element.

After the traversal is completed, it is the result of the movement.

public class LeetCode_283 {
    public static void moveZeroes(int[] nums) {
        // 最后一个非0的位置
        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("-----移动前-----");
        for (int num : nums) {
            System.out.print(num + " ");
        }
        System.out.println();
        moveZeroes(nums);
        System.out.println("-----移动后-----");
        for (int num : nums) {
            System.out.print(num + " ");
        }
    }
}
[Daily Message] The uncertainty of life is the source of our hope.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!