LeetCode 1089. Duplicate Zeros

Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.

Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= arr.length <= 104
  • 0 <= arr[i] <= 9

这题要求把一个数组中所有的0后面都加一个0,给我看懵了。

首先第一个想法是java里要怎么extend一个数组……然后仔细看了一下题才发现,它让你加了0以后超出数组长度范围的直接不管了,于是,还是不会。于是,就去直接抄答案了。

这个解法比较清晰直观易懂:https://leetcode.com/problems/duplicate-zeros/solutions/312743/java-c-o-n-o-1/

首先先计算一共有多少0,就能知道需要extend这个数组多长。然后巧妙的地方来了。如果我们从后往前来insert 0的话,就不需要像从前往后那样每次都要把后面所有的数字都移动一遍,大大节省了时间。那么问题又来了,从后面开始的话,那最后面的几个数字在加0以后大概率要被遗留在数组外了,咋整?那遗留在数组外就遗留呗,不往里写就完事了,妙啊。

于是搞懂思路以后代码写起来也比较容易了。相当于还是two pointers,一个指向加完0以后的末尾,一个指向原数组的末尾,把原数组的末尾往加完0以后的末尾copy就完事了,就是需要判断一下如果加完0以后的末尾是溢出的部分就不往里写。

class Solution {
    public void duplicateZeros(int[] arr) {
        int count = 0;
        for (int num : arr) {
            if (num == 0) {
                count++;
            }
        }

        int newLast = arr.length + count - 1;
        int oldLast = arr.length - 1;
        while (newLast >= 0 && oldLast >= 0) {
            if (newLast < arr.length) {
                arr[newLast] = arr[oldLast];
            }
            newLast--;
            if (arr[oldLast] == 0) {
                if (newLast < arr.length) {
                    arr[newLast] = 0;
                }
                newLast--;
            }
            oldLast--;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值