LeetCode热题100-颜色分类

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

我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。

必须在不使用库内置的 sort 函数的情况下解决这个问题。

题目要求不能排序,那想到的方法只能是双指针的方法,可以仿照之前的思路,使用快慢指针。时间复杂度3n。

python 复制代码
class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        if not nums:
            return
        
        def points_type(nums, k):
            slow = 0
            for fast in range(len(nums)):
                if nums[fast] != k:
                    nums[slow], nums[fast] = nums[fast], nums[slow]
                    slow += 1
        
        colors = [0, 1, 2]
        for color in colors:
            points_type(nums, color)

这里使用时间复杂度为On的进行1次遍历,主要确定0/2的位置完整的话,1的位置也是完整的。

python 复制代码
class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        if not nums:
            return
        
        left = 0
        right = len(nums) - 1
        i = 0
        while i <= right:

            if nums[i] == 0:
                nums[left], nums[i] = nums[i], nums[left]
                left += 1
                i += 1
                # 交换后这里是left值正常是0
            elif nums[i] == 2:
                nums[right], nums[i] = nums[i], nums[right]
                right -= 1
                # 交换后这里为right值需要检查
            else:
                i += 1
  
相关推荐
小羊没烦恼!29 分钟前
.NET 11 Runtime Async 详解
java·运维·开发语言·javascript·python
染指11101 小时前
152.Agent-LangGraph-Command的参数
人工智能·python·langchain·agents
小O的算法实验室1 小时前
ASOC,分层分数阶粒子群算法+无人机电场路径规划
算法
傅科摆 _ py1 小时前
链表力扣复习
数据结构·leetcode·链表
重生之小比特1 小时前
【算法拾光】二分查找|搜索插入位置 + x 的平方根
算法
第404号工位1 小时前
“已彻底删除”的照片与文件到底去哪了?我用底层扇区扫描,扒出手机和电脑的幽灵数据
linux·python·架构
智购科技自动售卖机厂家1 小时前
双摄像头方案F1-score只有0.85,排查发现是上下视角的融合逻辑写反了~YH
python·单片机·嵌入式硬件·算法·eclipse
田里的水稻1 小时前
FA_CNN卷积神经网络二---PyTorch
人工智能·pytorch·python·深度学习·cnn
小肝一下2 小时前
1.大模型介绍
python·langchain·大模型·ollama·langgrap
xiangjiaodalishi2 小时前
从 0 到 1 搭建 AI 友好的网站结构:信息架构与 GEO 的交叉地带
人工智能·python