[leetcode.com]算法题目 - Sort Colors
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library's sort function for this problem.
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with an one-pass algorithm using only constant space?

1 class Solution { 2 public: 3 void swap(int &a, int &b){ 4 int temp = a; 5 a = b; 6 b = temp; 7 } 8 void sortColors(int A[], int n) { 9 // Start typing your C/C++ solution below 10 // DO NOT write int main() function 11 if (n<2) return; 12 13 int first = 0; 14 int last = n-1; 15 while(first<n && 0==A[first]) 16 first++; 17 while(last>=0 && 2==A[last]) 18 last--; 19 20 int i=first; 21 while(first < last && i<=last){ 22 if (2==A[i]){ 23 swap(A[i],A[last]); 24 last--; 25 while(last>=0 && 2==A[last]) 26 last--; 27 }else if(0==A[i]){ 28 swap(A[i],A[first]); 29 first++; 30 if(i<first) i=first; 31 while(first<n && 0==A[first]) 32 first++; 33 }else{ 34 i++; 35 } 36 } 37 } 38 };
思路:如果只需要一次遍历,就地排序,其实在循环到每个数的时候要比两次遍历多做一些事情。因为0肯定是排在前面的,2肯定是排在后面的,指定两个指针,分别指向数组的两头,然后往中间缩进,注意分别讨论遍历到0,1,2时应该做何种运算,何种操作即可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)