栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Python

python:删除有序数组中的重复项

Python 更新时间:发布时间: 百科书网 趣学号

该题仍然采用快慢指针,但先要提前设置。若快慢指针所指向元素相等,则快指针向前移动一位,慢指针不动,再次判断,直至快慢指针所指向元素不相等,则慢指针向前移动一位让快指针所指元素进行覆盖。
方法一

# -*- coding: utf-8 -*-
"""
@Time    : 2022/8/5 16:05
@Author  : FJC
@File    : 删除有序数组中的重复项2.py
@Software: win10  python3.7
"""
class Solution:
    def removeDuplicates(self,nums):
        slow=0
        n=len(nums)
        for fast in range(n):
            if nums[fast]==nums[slow]:
                continue
            else:
                nums[slow+1]=nums[fast]
                slow+=1
        print(slow+1)
        return nums

solution = Solution()
print(solution.removeDuplicates([0, 1, 2, 2, 2,3,4]))

方法二

# -*- coding: utf-8 -*-
"""
@Time    : 2022/8/5 15:20
@Author  : FJC
@File    : 删除有序数组中的重复项1.py
@Software: win10  python3.7
"""
class Solution:
    def removeDuplicates(self,nums):
        slow=0
        n=len(nums)
        for fast in range(1,n):
            print(fast)
            if nums[fast] != nums[slow]:
                if nums[fast]-nums[slow]>0:
                    nums[slow+1] = nums[fast]
                    slow += 1
        print(slow+1)
        return nums

solution = Solution()
print(solution.removeDuplicates([0, 1, 2, 2, 2,3,4]))

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/1033416.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号