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
  
相关推荐
Thanks_ks17 小时前
提示词工程实战:用结构化提示词让大模型输出稳定可控
python·大模型·json·openai·提示词工程·deepseek·系统提示词
BK贝壳19 小时前
布尔数组也能做按位取反、移位和乘法:bool-hybrid-array 的位运算在本机跑了一遍
开发语言·数据结构·python·性能优化·numpy
ZhengEnCi19 小时前
前端日志和后端日志怎么记:分级、JSON 格式、按天分文件与保留策略
前端·后端·python
人间乄惊鸿客21 小时前
c++ 右值
c++·算法
fanstuck1 天前
AI 客服答错了,三分钟分清是 Prompt 还是系统的锅
算法
田里的水稻1 天前
FA_编程算法200个分类列数-SUM
算法·分类·数据挖掘
用户0332126663671 天前
使用 Python 为 PDF 文件添加页眉页脚
python
xurileidian1 天前
第 17 篇 · 边玩边学Python · for 遍历 enumerate 与 zip
java·前端·python
郝学胜-神的一滴1 天前
Effective Python 条款45:巧用属性注解平滑升级类属性
运维·开发语言·数据库·python·网络协议·numpy