1089. 复写零(简单)- LeetCode

题目描述

在这里插入图片描述

自己解法

对于就地算法的理解不够,就地修改要求空间复杂度为 O ( 1 ) O(1) O(1)。自己的解法虽然时间性能较好,但空间复杂度为 O ( n ) O(n) O(n),不符合题目要求,Python代码:

class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        """
        old = arr[:]
        temp = 0
        zero_count = [0] * len(arr)
        for i in range(len(arr)):
            if arr[i] == 0:
                temp += 1
            arr[i] = 0
            zero_count[i] = temp
        
        for i in range(len(arr)):
            if i+zero_count[i] >= len(arr):
                break
            if zero_count[i] > 0:
                arr[i+zero_count[i]] = old[i]
            else:
                arr[i] = old[i]       

在这里插入图片描述

官方解答

官方解答的思路是计算由于复制0导致原数组丢失元素的个数,找到最终数组的最后一个元素,然后倒序遍历,具体参考:官方解答

class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        """

        possible_dups = 0
        length_ = len(arr) - 1

        # Find the number of zeros to be duplicated
        for left in range(length_ + 1):

            # Stop when left points beyond the last element in the original list
            # which would be part of the modified list
            if left > length_ - possible_dups:
                break

            # Count the zeros
            if arr[left] == 0:
                # Edge case: This zero can't be duplicated. We have no more space,
                # as left is pointing to the last element which could be included  
                if left == length_ - possible_dups:
                    arr[length_] = 0 # For this zero we just copy it without duplication.
                    length_ -= 1
                    break
                possible_dups += 1

        # Start backwards from the last element which would be part of new list.
        last = length_ - possible_dups

        # Copy zero twice, and non zero once.
        for i in range(last, -1, -1):
            if arr[i] == 0:
                arr[i + possible_dups] = 0
                possible_dups -= 1
                arr[i + possible_dups] = 0
            else:
                arr[i + possible_dups] = arr[i]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值