Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

1089. Duplicate Zeros #62

Open Tcdian opened 4 years ago

Tcdian commented 4 years ago

1089. Duplicate Zeros

给你一个长度固定的整数数组 arr,请你将该数组中出现的每个零都复写一遍,并将其余的元素向右平移。

注意:请不要在超过该数组长度的位置写入元素。

要求:请对输入的数组 就地 进行上述修改,不要从函数返回任何东西。

Example 1

Input: [1,0,2,3,0,4,5,0]
Output: null
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]

Example 2

Input: [1,2,3]
Output: null
Explanation: After calling your function, the input array is modified to: [1,2,3]

Constraints

Tcdian commented 4 years ago

Solution

func duplicateZeros(arr []int) {
    length := len(arr);
    count := 0;
    for i := 0; i < length; i++ {
        if arr[i] == 0 {
            count++;
        }
    }
    copy := func(i int, j int) {
        if j < length {
            arr[j] = arr[i];
        }
    }
    i, j := length - 1, length + count - 1;
    for i < j {
        copy(i, j);
        if arr[i] == 0 {
            j--;
            copy(i, j);
        }
        i--;
        j--;
    }
}