LeetCode热题100-颜色分类

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

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

必须在不使用库内置的 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
  
相关推荐
cup112 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi004 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵6 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf7 小时前
Agent 流程编排
后端·python·agent
copyer_xyf7 小时前
Agent RAG
后端·python·agent
copyer_xyf7 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf8 小时前
Agent 记忆管理
后端·python·agent
JieE21215 小时前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python