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

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

给定 st 两个字符串,当它们分别被输入到空白的文本编辑器后,如果两者相等,返回 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前面
相关推荐
孟健6 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞8 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽11 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程15 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪15 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook16 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python