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()

相关推荐
言乐67 小时前
Python实现自动拉人脚本示例
开发语言·windows·python·django·pygame
归去来 兮8 小时前
Python爬虫爬取数据案例
开发语言·爬虫·python
何以解忧,唯有..8 小时前
Python logging 模块:从入门到精通
python·microsoft·php
quantdash_cc8 小时前
历史数据断层与REST请求慢到崩溃?QuantDash高性能量化数据API终极解决方案
开发语言·python·缓存·php·量化·quantdash
熊野君8 小时前
Prompt / RAG / 规则 / Skills —— 定位、协作与实现路线
开发语言·python
zhangphil9 小时前
Python Web后端框架FastAPI vs Flask
python·ai·llm
土司大王9 小时前
LeetCode hot100——相交链表
算法·leetcode·链表
土司大王9 小时前
LeetCode hot100——回文链表
算法·leetcode·链表
ly76899 小时前
XML 从入门到实践:语法、命名空间、XPath、XSD 与 Java 安全解析
xml·java·python