leecode——remove duplicate in-place(26)

给定一个已经排好序的数组,原位去重,并返回去重后数组的长度。问题的要求是不能用数组的copy,也就是空间复杂度为 O ( 1 ) O(1) O(1)

比如:[0,0,1,1,2]原位去重后的数组的前3个数分别是0,1,2,返回的长度为3。

思路:
难点再于in-place,但是解题的出发点也在in-place,既然是原位。如上面的例子,一个长度是5的数组,去重的前三个位置放0,1,2,那么其它数去哪儿了,所以只能是来交换或赋值。
关键是定义两个指针,一个是要求的已经去重的数组的指针,另一个是原来的数组遍历时的指针。
实现中,把交换优化为了赋值。

先画一下:
在这里插入图片描述

# -*- coding: utf-8 -*-
from typing import List


def removeDuplicate(nums: List[int]) -> int:
    """
    remove duplicate num of a sorted array in-place which is passed in, and return the new
    length of array
    :param nums:
    :return:
    """
    target_idx = 0
    remove_idx = 1
    for i in range(len(nums)):
        if remove_idx == len(nums):
            break
        if nums[remove_idx] > nums[target_idx]:
            nums[target_idx + 1], nums[remove_idx] = nums[remove_idx], nums[target_idx + 1]
            target_idx += 1
            remove_idx += 1
        else:
            remove_idx += 1

    return target_idx + 1


def removeDuplicate2(nums: List[int]) -> int:
    """
    remove duplicate num of a sorted array in-place which is passed in, and return the new
    length of array
    :param nums:
    :return:
    """
    target_idx = 0
    remove_idx = 1
    for i in range(len(nums)):
        if remove_idx == len(nums):
            break
        if nums[remove_idx] > nums[target_idx]:
            # 把交换优化为赋值
            nums[target_idx + 1] = nums[remove_idx]
            target_idx += 1
            remove_idx += 1
        else:
            remove_idx += 1

    return target_idx + 1


def removeDuplicate3(nums: List[int]) -> int:
    """
    remove duplicate num of a sorted array in-place which is passed in, and return the new
    length of array
    :param nums:
    :return:
    """
    # 优化了两个指针的写法,用j直接作为要比较的指针,另外定义一个指针
    i = 0
    for j in range(1, len(nums)):
        if nums[j] > nums[i]:
            nums[i + 1] = nums[j]
            i += 1
    return i + 1


if __name__ == '__main__':
    l = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
    # [0,1,0,1,1, 2,2,3,3,4]

    # [0,1,2,3,4,0,1,2,3]
    print(removeDuplicate2(l))
    print(l)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值