您的浏览器不支持html5的canvas

算法-每日一练

题目:

给定一个固定长度的整数数组arr,每次数显0时重复一次,将剩余的元素向右移动。
超出原始数组长度的元素不会被写入。
eg:int[1,0,2,3,0,4,5,0]-->[1,0,0,2,3,0,0,4]

answer:

public static void duplicateZeros(int[] arr) {
    int possibleDups = 0; // 找出重复0的个数
    int length_ = arr.length - 1;//下标
    // Find the number of zeros to be duplicated   找出重复0的个数
    //当下标超出原来数组的最后一个元素时停止
    for (int left = 0; left <= length_ - possibleDups; left++) {
        if (arr[left] == 0) {
            //边缘情况,这个0不能被复制,没有空间了
            //As left是指向最后一个可以包含的元素
            if (left == length_ - possibleDups) {
                // 这个0我们只赋值他不修改位置
                arr[length_] = 0;
                length_ -= 1;
                break;
            }
            possibleDups++;
        }
    }

    //  从新数组的最后一个元素开始
    int last = length_ - possibleDups;

    // 0赋值两次,不是0的赋值一次
    for (int i = last; i >= 0; i--) {
        if (arr[i] == 0) {
            //新加一个0;
            arr[i + possibleDups] = 0;
            possibleDups--;
            arr[i + possibleDups] = 0;
        } else {
            arr[i + possibleDups] = arr[i];
        }
    }


    //结果展示
    for (int a : arr){
        System.out.print(a);
    }
}
posted @ 2021-09-03 09:29  呵呵哒灬荒唐  阅读(56)  评论(0)    收藏  举报