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前面
相关推荐
加油吧zkf3 分钟前
AI大模型如何重塑软件开发流程?——结合目标检测的深度实践与代码示例
开发语言·图像处理·人工智能·python·yolo
t_hj4 分钟前
python规划
python
czhc114007566319 分钟前
Linux 76 rsync
linux·运维·python
悠悠小茉莉1 小时前
Win11 安装 Visual Studio(保姆教程 - 更新至2025.07)
c++·ide·vscode·python·visualstudio·visual studio
m0_625686551 小时前
day53
python
Real_man2 小时前
告别 requirements.txt,拥抱 pyproject.toml和uv的现代Python工作流
python
站大爷IP2 小时前
Python文件操作的"保险箱":with语句深度实战指南
python
运器1232 小时前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程
巴里巴气5 小时前
selenium基础知识 和 模拟登录selenium版本
爬虫·python·selenium·爬虫模拟登录
19895 小时前
【零基础学AI】第26讲:循环神经网络(RNN)与LSTM - 文本生成
人工智能·python·rnn·神经网络·机器学习·tensorflow·lstm