算法题——给定一个数组 arr,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

参考自:https://blog.csdn.net/qq_38200548/article/details/80688630

示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

  说明:

    1.必须在原数组上操作,不能拷贝额外的数组。
    2.尽量减少操作次数。
package suanfa;

public class demo2 {
    public static void main(String[] args) {
        //随便定义一个数组
        int[] arr={1,2,0,3,0,4,5,0};
        moveZeros(arr);
        for (int i : arr) {
            System.out.print(i+" ");
        }
    }
    private static void moveZeros(int[] arr) {
        //定义了两个快慢指针
        int slow=0,fast=0;
        while(fast<arr.length) {
            if (arr[fast] != 0) {
                arr[slow] = arr[fast];
                slow++;
                fast++;
            } else {// 一旦这个数组上的数字是0,那么fast指针就需要往前走
                   // slow指针停留在0这个位置,在等待着fast发现了非0的数字将0位置的slow指针覆盖掉
                fast++;
            }
        }
        // slow跟fast相差了多少,就说明这个数组有多少个0,在上面填充完元素之后,
        // 就需要将漏掉的0补上
        for (int i = slow; i <arr.length ; i++) {
            arr[i]=0;
        }
    }
}
 
 

猜你喜欢

转载自www.cnblogs.com/huozhonghun/p/9844340.html