当前位置: 首页 > ds >正文

【leetcode】75.颜色分类

文章目录

        • 1. 单指针
        • 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. 单指针
class Solution(object):def sortColors(self, nums):""":type nums: List[int]:rtype: None Do not return anything, modify nums in-place instead."""a = 0for i in range(len(nums)):if nums[i] == 0:nums[a], nums[i] = nums[i], nums[a]a += 1for i in range(a, len(nums)):if nums[i] == 1:nums[a], nums[i] = nums[i], nums[a]a += 1return nums
2. 非原地(数组)
class Solution(object):def sortColors(self, nums):""":type nums: List[int]:rtype: None Do not return anything, modify nums in-place instead."""red = 0white =0blue = 0for color in nums:if color == 0:red += 1elif color == 1:white += 1else:blue += 1nums[:red] = [0] * rednums[red: red + white] = [1] * whitenums[red + white: ] = [2] * blue
http://www.xdnf.cn/news/8021.html

相关文章:

  • leetcode 3356. 零数组变换 II 中等
  • windows安装python环境
  • Supplemental Table 5FAM49B H-SCORE与其他临床特征的关系
  • Win11上安装docker
  • 技术管理专题学习笔记-技术管理中的障碍和应对(2)
  • 【3. 无重复字符的最长子串】
  • 力扣-三数之和
  • 融云 uni-app IMKit 上线,1 天集成,多端畅行
  • 在 Excel xll 自动注册操作 中使用东方仙盟软件2————仙盟创梦IDE
  • 时钟树:概念与编程详解 (铁头山羊)
  • 人工智能小白转型学习指南
  • 对单调栈的理解
  • Spring IOCDI————(2)
  • Linux | tmux | 无法复制粘贴
  • C++类和对象(2)
  • PyTorch学习之:torch.gather是什么?
  • 海康NVR录像回放SDK原始流转FLV视频流:基于Java的流媒体转码(无需安装第三方插件ffmpeg)
  • 远程访问家里的路由器:异地访问内网设备或指定端口网址
  • 芯片分享之X5045PI性能介绍
  • Backbone
  • Typescript 教程
  • Baklib智启企业AI知识管理
  • MySQL 主从复制搭建全流程:基于 Docker 与 Harbor 仓库
  • 杂记10---ldd获取依赖so名称并导出txt文件
  • 数字电子技术基础(六十二)——使用Multisim软件绘制边沿触发的D触发器和JK触发器
  • 2025年 PMP 6月 8月 专题知识
  • Python数据分析基础
  • LangChain入门和应用#1
  • 工商总局可视化模版-Echarts的纯HTML源码
  • CMake跨平台编译生成:从理论到实战