1.3 面试经典150题 - 删除有序数组中的重复项

删除有序数组中的重复项

python 复制代码
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        # 处理边界数据
        if not nums: return 0
        if len(nums) == 1: return 1
        # 两个指针,一个记录当前有多少个不重复值的个数,一个记录最新遍历到的值
        count = 1
        tmp = nums[0]
        for i in range(1, len(nums)):
            if nums[i] == tmp:
                continue
            # 遍历到新的值时,更新指针
            tmp = nums[i]
            nums[count] = tmp
            count += 1
        # 切分原数据,并返回结果
        nums = nums[:count]
        return count

删除有序数组中的重复项 II

针对上面的解答,略加改造

python 复制代码
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        # 处理边界数据
        if not nums: return 0
        if len(nums) == 1: return 1
        # 三个指针,一个记录当前数组中应该有的值的个数,一个记录最新遍历到的值,一个记录重复次数
        count = 1
        tmp = nums[0]
        tmp_count = 1
        for i in range(1, len(nums)):
            if nums[i] == tmp:
                # 增加重复次数计数
                tmp_count += 1
                if tmp_count > 2:
                    # 超过2次时,不记录在数组了
                    continue
            else:
                # 更新值和重复次数
                tmp = nums[i]
                tmp_count = 1
            # 更新数组的值,并更新值个数的指针
            nums[count] = tmp
            count += 1
        # 切分原数据,并返回结果
        nums = nums[:count]
        return count
相关推荐
wuyk5552 小时前
Spider-第14讲-表单提交与CSRF
前端·爬虫·python·elasticsearch·csrf
汤姆宝库2 小时前
RoPE旋转位置编码的实现与长上下文外推
python·深度学习·机器学习
用户019027581613 小时前
股票代码格式对照:各数据源代码转 AlphaFeed
python
__underline__3 小时前
冷门Python知识点005篇:list.sort( )的排序稳定性,是用0字节额外内存实现的
python·算法
贝壳6903 小时前
升到 9.13.12 我照着文档抄了两行,两次都炸了
python
VIP_CQCRE4 小时前
AI 音乐 API 上线后成本失控?用预算阈值、幂等任务和音频验收管住 Suno v6
python·api·suno·ai音乐·成本治理
2601_967980114 小时前
python list如何赋值
python·list·列表推导式·赋值·切片赋值
典学长编程5 小时前
LangGraph 快速入门:从 StateGraph 到 ReAct Agent
python·有向图·无向图·langgraph·react agent·stategraph
用户019027581617 小时前
AlphaFeed 查不到代码返回空?非法/缺后缀 symbol 的行为与处理
python
isfox8 小时前
Python 单元测试:别再用 print 调试了,写个测试一劳永逸
python