sort-colors颜色分类——排序3种数字 tag 数组
题目描述
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?
即将0、1、2的序列按顺序排好。
【扫描两遍的计数排序】
1 public class Solution { 2 public void sortColors(int[] A) { 3 int i, r, w, b; 4 r = w = b = 0; 5 for (i = 0; i < A.length; i++) { 6 if (A[i] == 0) r++; 7 else if (A[i] == 1) w++; 8 else b++; 9 } 10 for (i = 0; i < A.length; i++) { 11 if (i < r) A[i] = 0; 12 else if (i < r + w) A[i] = 1; 13 else A[i] = 2; 14 } 15 } 16 }
【扫描一遍,单向遍历】
注意,l记录0区,r记录2区的边界。因此循环遍历到i<=r即可。
1 class Solution { 2 public: 3 void swap(int A[], int i, int j){ 4 int tmp=A[i]; 5 A[i]=A[j]; 6 A[j]=tmp; 7 } 8 void sortColors(int A[], int n) { 9 int l=0,r=n-1; 10 for(int i=0;i<=r;i++){ 11 if(A[i]==0){ 12 swap(A,i,l); 13 l++; 14 } 15 else if(A[i]==2){ 16 swap(A,i,r); 17 r--; 18 i--; 19 } 20 } 21 } 22 };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
分类:
leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了