【leetcode】75.颜色分类

文章目录

        • [1. 单指针](#1. 单指针)
        • [2. 非原地(数组)](#2. 非原地(数组))

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

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

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

示例 1:

输入:nums = [2,0,2,1,1,0]

输出:[0,0,1,1,2,2]

示例 2:

输入:nums = [2,0,1]

输出:[0,1,2]

1. 单指针
python 复制代码
class Solution(object):
    def sortColors(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        a = 0
        for i in range(len(nums)):
            if nums[i] == 0:
                nums[a], nums[i] = nums[i], nums[a]
                a += 1
        
        for i in range(a, len(nums)):
            if nums[i] == 1:
                nums[a], nums[i] = nums[i], nums[a]
                a += 1
        return nums

  
2. 非原地(数组)
python 复制代码
class Solution(object):
    def sortColors(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        red = 0
        white =0
        blue = 0
        for color in nums:
            if color == 0:
                red += 1
            elif color == 1:
                white += 1
            else:
                blue += 1
        nums[:red] = [0] * red
        nums[red: red + white] = [1] * white
        nums[red + white: ] = [2] * blue
        
相关推荐
清铎27 分钟前
leetcode_day12_滑动窗口_《绝境求生》
python·算法·leetcode·动态规划
linweidong32 分钟前
嵌入式电机:如何在低速和高负载状态下保持FOC(Field-Oriented Control)算法的电流控制稳定?
stm32·单片机·算法
踩坑记录38 分钟前
leetcode hot100 42 接雨水 hard 双指针
leetcode
net3m331 小时前
单片机屏幕多级菜单系统之当前屏幕号+屏幕菜单当前深度 机制
c语言·c++·算法
mmz12071 小时前
二分查找(c++)
开发语言·c++·算法
Insight1 小时前
拒绝手动 Copy!一文吃透 PyTorch/NumPy 中的广播机制 (Broadcasting)
算法
CoovallyAIHub1 小时前
工业视觉检测:多模态大模型的诱惑
深度学习·算法·计算机视觉
Jayden_Ruan1 小时前
C++分解质因数
数据结构·c++·算法
bubiyoushang8882 小时前
MATLAB实现雷达恒虚警检测
数据结构·算法·matlab
wu_asia2 小时前
编程技巧:如何高效输出特定倍数数列
c语言·数据结构·算法