LeetCode Remove Duplicates from Sorted Array

LeetCode解题之Remove Duplicates from Sorted Array


原题

从一个有序的数组中去除重复的数字,返回处理后的数组长度。

注意点:

  • 只能用常量的额外空间
  • 将不重复的数字移到数组前部,剩余的部分不需要处理

例子:

输入: nums = [1, 1, 2]
输出: 2

解题思路

用一个下标index来标记下一个不重复的数字存放的位置,另一个下标start来表示当前是和哪个数字来比较有没有重复。遍历数字,如果不重复则放到index位置,后移index,并更新start位置;否则继续遍历。返回index即为不重复数组的长度。

AC源码

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        # The index where the character needs to be placed
        index = 1
        # The index of repeating characters
        start = 0
        for i in range(1, len(nums)):
            if nums[start] != nums[i]:
                nums[index] = nums[i]
                index += 1
                start = i
        return index


if __name__ == "__main__":
    assert Solution().removeDuplicates([1, 1, 2]) == 2

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值