LeetCode 题解工作台

复写零

给你一个长度固定的整数数组 arr ,请你将该数组中出现的每个零都复写一遍,并将其余的元素向右平移。 注意:请不要在超过该数组长度的位置写入元素。请对输入的数组 就地 进行上述修改,不要从函数返回任何东西。 示例 1: 输入: arr = [1,0,2,3,0,4,5,0] 输出: [1,0,0,2…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 双·指针·invariant

bolt

答案摘要

开辟一个等长数组,将 `arr` 复刻一份,再进行简单模拟即可。 - 时间复杂度:。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

注意:请不要在超过该数组长度的位置写入元素。请对输入的数组 就地 进行上述修改,不要从函数返回任何东西。

 

示例 1:

输入:arr = [1,0,2,3,0,4,5,0]
输出:[1,0,0,2,3,0,0,4]
解释:调用函数后,输入的数组将被修改为:[1,0,0,2,3,0,0,4]

示例 2:

输入:arr = [1,2,3]
输出:[1,2,3]
解释:调用函数后,输入的数组将被修改为:[1,2,3]

 

提示:

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

解题思路

方法一:模拟

开辟一个等长数组,将 arr 复刻一份,再进行简单模拟即可。

  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(n)O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        """
        n = len(arr)
        i, k = -1, 0
        while k < n:
            i += 1
            k += 1 if arr[i] else 2
        j = n - 1
        if k == n + 1:
            arr[j] = 0
            i, j = i - 1, j - 1
        while ~j:
            if arr[i] == 0:
                arr[j] = arr[j - 1] = arr[i]
                j -= 1
            else:
                arr[j] = arr[i]
            i, j = i - 1, j - 1
speed

复杂度分析

指标
时间complexity is O(N) because each element is scanned at most twice, and space complexity is O(1) since all operations modify the array in place without extra arrays or buffers.
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Are you tracking how duplicating zeros affects element positions?

  • question_mark

    Can you solve this in-place without extra storage?

  • question_mark

    How do you handle zeros at the end that would overflow the array?

warning

常见陷阱

外企场景
  • error

    Overwriting elements before they are duplicated when scanning left to right.

  • error

    Failing to handle zeros at the last valid index correctly, causing array overflow.

  • error

    Using extra arrays which violates the in-place modification requirement.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Duplicate a specific value other than zero while shifting elements in place.

  • arrow_right_alt

    Duplicate zeros but allow dynamic array expansion instead of fixed length.

  • arrow_right_alt

    Count the total duplicates of zeros without modifying the original array in place.

help

常见问题

外企场景

复写零题解:双·指针·invariant | LeetCode #1089 简单