leetcode 1089. Duplicate Zeros 解法 Python

本文探讨了在固定长度数组中遇到零时如何将其复制并保持其他元素不变的问题,提供了两种解决方案:一是使用额外空间进行元素复制,二是通过时间换空间的方式在原数组上操作。详细介绍了每种方法的实现过程及时间复杂度。
Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

一.问题描述

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就加两个0进去。

时间复杂度为O(N)

第二种方法是时间换空间,碰到0就加两个0到当前数组,然后后面的元素一个个向后移,有点像冒泡排序。

时间复杂度为O(N*N)

这道题要注意的是当用第一张方法的时候,记得要直接改变arr指向的值,而不是改变它引用本身,因为leetcode判定程序还是记录着一开始的引用值,可以去了解一下leetcode的变量引用机制。

给出两种实现方法。

更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我

欢迎大家一起套路一起刷题一起ac。

三.源码

1.新开数组

class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        """
        len_arr=len(arr)
        rst=[]
        for num in arr:
            if num==0:
                rst.append(0)
                rst.append(0)
            else:rst.append(num)
            if len(rst)>=len_arr:
                arr[:]=rst[:len_arr]
                # arr=rst[:len_arr] this do not work
                break

2.往后移动

class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        """
        i=0
        while i<len(arr):
            if arr[i]==0:
                arr.pop() # O(1)
                arr.insert(i+1,0) # O(N)
                i+=2
            else:i+=1

 

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值