Leetcode:移动0

问题描述:
给定一个数组 nums, 编写一个函数将所有 0 移动到它的末尾,同时保持非零元素的相对顺序。
例如, 定义 nums = [0, 1, 0, 3, 12],调用函数之后, nums 应为 [1, 3, 12, 0, 0]。
注意事项:
必须在原数组上操作,不要为一个新数组分配额外空间。
尽量减少操作总数。
算法基本思想:
1.外层设置循环从后往前寻找0元素。

2.找到0元素,就将其值赋给临时变量temp;然后将其后所有元素前移一位,将0元素覆盖。

3.将temp放到数组最后一位。

4.i--;继续循环找下一个0元素。

public class Yidongling {
    public static void moveZeroes(int nums[]) {
        for (int i = nums.length - 1; i >= 0; i--) {
            int temp = 0;
            if (nums[i] == 0) {
                temp = nums[i];
                for (int j = i; j < nums.length - 1; j++)
                    nums[j] = nums[j + 1];
                nums[nums.length - 1] = temp;
            }
        }
        for (int i = 0; i < nums.length; i++) {
            System.out.println(nums[i]);
        }
    }

    public static void main(String[] args) {
        int A[] = {0, 1, 0, 3, 12};
        moveZeroes(A);
    }
}


猜你喜欢

转载自blog.csdn.net/qq_38202756/article/details/81036844