【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
        
相关推荐
人间乄惊鸿客14 小时前
c++ 右值
c++·算法
fanstuck15 小时前
AI 客服答错了,三分钟分清是 Prompt 还是系统的锅
算法
田里的水稻16 小时前
FA_编程算法200个分类列数-SUM
算法·分类·数据挖掘
猿人谷18 小时前
从百万个 Pareto 解中选出 100 个:Riesz s-Energy 如何实现高效的多样性选择?
后端·算法·aigc
地平线开发者18 小时前
地平线 × 同济无人车队:PointPillars 从浮点模型到 BPU 部署
算法·自动驾驶
iiiiii1119 小时前
从最大熵到 SAC:Soft Q-Learning 与 Soft Actor-Critic 公式推导笔记
人工智能·笔记·算法·机器学习·强化学习
田里的水稻19 小时前
FA_排序算法-冒泡排序
java·算法·排序算法
AAA修煤气灶刘哥1 天前
AI 写的 SQL 跑通了,为什么和财务报表对不上?
人工智能·后端·算法