python代码练习:双指针法

题目一:移除元素

给你一个数组 nums和一个值 val,你需要 原地 移除所有数值等于 val的元素,并返回移除后数组的新长度。

不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地修改输入数组。

元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

python 复制代码
from typing import List
class Solution:
    def removeElement(cls, nums: List[int], val: int) -> int:
        fast = slow = 0
        while fast<len(nums):
            if nums[fast] != val:
                nums[slow]=nums[fast]
                fast=fast+1
                slow=slow+1
            else:
                fast=fast+1
        return slow

if __name__ == '__main__':
    s=Solution()
    s.removeElement(nums=[1,2,3,4,2,3,4],val=2)

题目二:删除有序数组中的重复项

给你一个 非严格递增排列 的数组 nums ,请你**原地** 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。元素的 相对顺序 应该保持 一致 。然后返回 nums 中唯一元素的个数。

python 复制代码
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        slow=0
        fast=1
        while fast<len(nums):
            if nums[slow]==nums[fast]:
                fast=fast+1
            else:
                slow=slow+1
                nums[slow]=nums[fast]
                fast=fast+1
        return slow+1

题目三:删除有序数组中的重复项 II

给你一个有序数组 nums ,请你**原地** 删除重复出现的元素,使得出现次数超过两次的元素只出现两次 ,返回删除后数组的新长度。

python 复制代码
from typing import List
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        slow=0
        fast=1
        count=1
        while fast<len(nums):
            if nums[slow] == nums[fast]:
                count=count+1
                if count<=2:
                    slow=slow+1
                    nums[slow]=nums[fast]
                    fast=fast+1
                else:
                    fast = fast + 1
            elif nums[slow] != nums[fast] :
                count=1
                slow = slow+1
                nums[slow] = nums[fast]
                fast = fast+1
            print(nums)
        print(slow+1)
        return slow+1

if __name__ == '__main__':
    s=Solution()
    s.removeDuplicates(nums=[1,1,1,2,2,2,3])

优化:

python 复制代码
from typing import List
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        slow=2
        fast=2
        while fast<len(nums):
            if nums[fast] != nums[slow-2]:
                nums[slow]=nums[fast]
                slow=slow+1
                fast=fast+1
            else:
                fast=fast+1
        return slow

if __name__ == '__main__':
    s=Solution()
    s.removeDuplicates(nums=[1,1,1,2,2,2,3])

题目四:移动零

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

请注意 ,必须在不复制数组的情况下原地对数组进行操作。

python 复制代码
from typing import List
class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        slow=0
        for fast in range(len(nums)):
            if nums[fast] != 0:
                nums[slow] = nums[fast]
                slow=slow+1

        for item in  range(slow,len(nums)):
            nums[item]=0
        return nums
    
s=Solution()
print(s.moveZeroes(nums=[0,1,0,3,4,7]))

# 不为0的先移到前面,后面的都补为0

题目五:比较含退格的字符串

给定 s 和 t 两个字符串,当它们分别被输入到空白的文本编辑器后,如果两者相等,返回 true 。# 代表退格字符。

**注意:**如果对空文本输入退格字符,文本继续为空。

python 复制代码
class Solution:
    def getString(self,sc):
        bz=[]
        for item in sc:
            if item != '#':
                bz.append(item)
            elif len(bz)>0:
                bz.pop()

        print(bz)
        return str(bz)
    def backspaceCompare(self, s: str, t: str) -> bool:
        return self.getString(sc=s) == self.getString(sc=t)

# 使用栈,等于#时就出栈(需要注意空栈时不能在出栈),不等于#时则入栈。

题目六:有序数组的平方

给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。

python 复制代码
from typing import List
class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        for i in range(len(nums)):
            nums[i] = nums[i]**2
        a=len(nums)-1
        low,high=0,a
        res = [-1]*len(nums)
        while low<=high:
            if nums[low]>nums[high]:
                res[a] = nums[low]
                low=low+1
            else:
                res[a] = nums[high]
                high = high-1
            a=a-1
        return res

s=Solution()
print(s.sortedSquares(nums=[-6,-4,-3,0,1,2,3,5]))
# 左右哦两端开始遍历,用一个列表来存放遍历结果。
# 原列表的low比high大,就把该数据放到res末尾
# 原列表low比high小,就把high放到res前面
相关推荐
VW_4046 分钟前
csdn-2026-11-23-第一站踩坑
爬虫·python
yiangL_23 分钟前
课后作业4:基于 Python 的古诗词词云可视化(P205)
开发语言·python
Dmz丶24 分钟前
前端转 AI 100 天 Day 52:RAG 项目实战(一)——从零搭建企业知识库
python
卷无止境4 小时前
用 SimPy 做离散事件仿真:时钟不走步,事件自己排队
后端·python
撸码猿5 小时前
数据采集场景的语序点选验证码:90.2% 整词准确率的本地 OCR 实践
python·ocr
用户0332126663675 小时前
使用 Python 在 Excel 中创建折线图和条形图
python·excel
木子欢儿7 小时前
Ubuntu 26.04 LTS 安装Python 3.12
linux·运维·服务器·python·ubuntu
Wellijohn7 小时前
Python 异步并发:我把 5 个坑踩完了,你照着抄模板就行
python
AI创界者7 小时前
Python 进阶实战(六十二章):分布式定时任务、异步工作流与幂等补偿机制实战
人工智能·python·aigc
炸薯条!9 小时前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python