【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
        
相关推荐
无敌最俊朗@19 分钟前
死锁 (Deadlock) 深度解析
算法
西阳未落38 分钟前
欧拉路径与欧拉回路
算法·深度优先
Swift社区1 小时前
LeetCode 390 消除游戏
算法·leetcode·游戏
橘颂TA2 小时前
【剑斩OFFER】优雅的解法——三数之和
算法
我爱工作&工作love我2 小时前
2024-CSP-J T3 小木棍
算法·动态规划
DatGuy2 小时前
Week 18: 深度学习补遗:Stacking和量子运算Deutsch算法
人工智能·深度学习·算法
Nie_Xun4 小时前
ROS1 go2 vlp16 局部避障--3 篇
算法
Da Da 泓7 小时前
LinkedList模拟实现
java·开发语言·数据结构·学习·算法
海琴烟Sunshine7 小时前
Leetcode 14. 最长公共前缀
java·服务器·leetcode
未知陨落7 小时前
LeetCode:68.寻找两个正序数组的中位数
算法·leetcode