leetcode 26. 删除有序数组中的重复项



解题思路:

使用list.count方法判断值是否重复,重复,则使用list.index方法找到重复值下标,使用list.pop方法删除对应的值,每删一个重复值,对应值重复次数-1

代码

python 复制代码
class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        t = len(nums)
        if t ==1:
            print(1)
            print(nums)
        elif t ==0:
            print(0)
            print([])
        else:
            for i in range(t-1):
                #加上if i<t-1,否则会报错
                if i<t-1:
                    count1 = nums.count(nums[i])
                while count1>1:
                    position=nums.index(nums[i],i+1)
                    nums.pop(position) 
                    count1-=1
                t = len(nums)
            print(t)
            print(nums)

ps:若无改变原列表要求,可以使用集合来去重 list(set(列表))或者增加一个列表,新的列表装无重复数据:依次从原列表区数据,判断新列表是否有对应数据,无则将数据添加至新列表,若使用pop()取出,记得倒置 reverse()

相关推荐
赵民勇16 小时前
Python 协程详解与技巧总结
python
极光代码工作室16 小时前
基于YOLO目标检测的智能监控系统
python·深度学习·yolo·机器学习·计算机视觉
江华森17 小时前
Python 进阶编程实战 — 从多版本环境到百万级登录系统
python
C+-C资深大佬17 小时前
python while循环
服务器·开发语言·python
wabs66617 小时前
关于动态规划【力扣1143.最长公共子序列的思考】
算法·leetcode·动态规划
剑挑星河月18 小时前
54.螺旋矩阵
java·算法·leetcode·矩阵
zh路西法18 小时前
【现代控制理论与卡尔曼滤波】从状态空间到Python仿真实现
开发语言·python
Vodka~18 小时前
WSL2 + RViz GPU渲染机械臂
人工智能·python
8Qi818 小时前
hello-agents学习笔记--Memory让Agent拥有记忆
人工智能·python·llm·agent·ai编程·vibecoding
Esaka_Forever19 小时前
Python 完整内存管理机制详解
开发语言·python·spring