【Leetcode】1089. Duplicate Zeros(第141周周赛)(模拟)

Given a fixed length array arr of integers, 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, do not return anything from your function.

 

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]

 

Note:

  1. 1 <= arr.length <= 10000
  2. 0 <= arr[i] <= 9

题目大意:

如果数组中遇到0我们将其多复制一次将之后数向后移动,长度不超过原始长度。

解题思路:

暴力即可,遇到零从后向前调整每一位。

 

class Solution {
public:
    void duplicateZeros(vector<int>& arr) {
        int cor_idx = 0;
        while(cor_idx<arr.size()){
            if(arr[cor_idx]==0 && cor_idx != arr.size()-1){
                
                int tmp_idx = arr.size()-1;
                while(tmp_idx >= cor_idx+2){
                    arr[tmp_idx] = arr[tmp_idx-1];
                    tmp_idx--;
                }
                arr[cor_idx+1] = 0;
                cor_idx += 2;
            }else{
                cor_idx++;
            }
        }
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值