leetcode双指针系列1: LC26删除有序数组中的重复项,LC674最长连续递增序列,LC27移除元素,LC80 删除有序数组中的重复项II,LC 283 移动零,LC75 颜色分类

双指针思想通常用来解决数组或者字符串的子序列问题,

使用双指针,左指针指向当前已经处理好的序列的尾部,右指针指向待处理序列的头部
在循环中,判断条件都是右指针所在位置,如果满足,会对右指针位置进行处理,然后放到左指针位置。

leetcode 26 删除有序数组中的重复项
leetcode 674 最长连续递增序列
leetcode 27 移除元素
leetcode 80 删除有序数组中的重复项 II
leetcode 283 移动零
leetcode 75 颜色分类

都可以用上述的思想解决问题。即,确定好已经处理好的部分,和将要处理的部分。
题目内容我就懒得描述了。。网上有很多,只给出答案。

leetcode26 删除有序数组中的重复项
输入:nums = [0,0,1,1,1,2,2,3,3,4]
输出:5, nums = [0,1,2,3,4]
解释:函数应该返回新的长度 5 , 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4 。不需要考虑数组中超出新长度后面的元素。

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if not nums:
            return 0
        
        n = len(nums)
        fast,slow = 1,1
        while fast < n:
            if nums[fast] != nums[fast - 1]:# 找切换点
                nums[slow] = nums[fast]
                slow += 1
            fast += 1
  
        return slow

leetcode 674 最长连续递增序列(的长度)

class Solution:
    def findLengthOfLCIS(self, nums: List[int]) -> int:
        n=len(nums)
        curr_len=1
        max_len=1
        i,j=0,1
        while jnums[i]:
                curr_len+=1
            else:
                curr_len=1
            max_len=max(curr_len,max_len)
            i+=1
            j+=1
        return max_len

leetcode 27 移除元素
输入:nums = [0,1,2,2,3,0,4,2], val = 2
输出:5, nums = [0,1,4,0,3]
解释:函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。注意这五个元素可为任意顺序。你不需要考虑数组中超出新长度后面的元素。

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        n=len(nums)
        if n==0:
            return 0
        slow,fast=0,0
        while fast

leetcode 283 移动零
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]

class Solution: # 参考leetcode 27 移除元素
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n=len(nums)
        i,j=0,0
        while j

leetcode 80 删除有序数组中的重复项 II
给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 最多出现两次 ,返回删除后数组的新长度。
输入:nums = [0,0,1,1,1,1,2,3,3]
输出:7, nums = [0,0,1,1,2,3,3]
解释:函数应返回新长度 length = 7, 并且原数组的前五个元素被修改为 0, 0, 1, 1, 2, 3, 3 。 不需要考虑数组中超出新长度后面的元素。

class Solution: #这个模板适用于每个元素最多出现任意次,只需要修改其中两行代码即可
    def removeDuplicates(self, nums: List[int]) -> int:
        n=len(nums)
        slow,fast=2,2
        while fast

leetcode 75 颜色分类
给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums ,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。

我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
必须在不使用库的sort函数的情况下解决这个问题。

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n=len(nums)
        i,j=0,0
        while j=0: #0移动到最左边
            if nums[i]!=0:
                if nums[j]==0:
                    nums[i],nums[j]=nums[j],nums[i]
                j-=1
            i-=1
        return nums

你可能感兴趣的:(leetcode,leetcode,算法)