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.

void sortColors(vector<int>& nums)
{//排序时间复杂度O(n)
int length=nums.size();
int zero=0;
int two=length-1;
while(zero<length && nums[zero]==0)
{//找到第一个不为0的数的下标
zero++;
}
while(two>=zero && nums[two]==2)
{//找到倒数第一个不为2的数的下标,zero前的数都是0
two--;
} for(int i=zero;i<=two;++i)
{
if(nums[i]==0)
{//假设为0,和zero指向的数交换,zero前移
nums[i]=1;//zero指向的值肯定是1,首先不可能为0,其次,i遍历过的地方,2都已经换到最后
nums[zero]=0;
zero++;
}
else if(nums[i]==1)
{//假设为1,则跳过
continue;
}
else
{//假设为2。则和two指向的数交换,并更新two的值。
//和zero不同,two前面的数可能还未排序
nums[i]=nums[two];
nums[two]=2;
two--;
while(two>=i && nums[two]==2)
{
two--;
}
i--;//先向后退一步。由于two指向的数还未进行排序
}
}
}

最新文章

  1. dbcp/c3p0连接池设置mysql会话变量
  2. 第8课 goto 和 void 分析
  3. QTP 10 安装及破解
  4. scrapy爬虫成长日记之将抓取内容写入mysql数据库
  5. Winform之ListView
  6. 经典的iptables shell脚本
  7. 第六篇、git常用的命令
  8. C# Double类型 不四舍五入
  9. 树莓派deian的linux常用命令
  10. iMac 无线键盘 无法配对
  11. luci-bwc
  12. Centos7-安装telnet服务
  13. Pycharm永久激活方式
  14. Xamarin SQLite教程数据库访问与生成
  15. cf 1041C双指针
  16. linux 系统 网卡 ethX没有显示IP的处理方式
  17. WTF小程序之原生遇见mpvue
  18. 对 JavaScript 中的5种主要的数据类型进行值复制
  19. C/C++——程序的内存分配
  20. ossfs工具将OSS挂载到阿里云linux系统目录例子

热门文章

  1. ACM_买粽子(UVA唯一的雪花)
  2. Beta冲刺-星期五
  3. android黑科技系列——Apk混淆成中文语言代码
  4. JavaScript编程题(一)
  5. MxNet教程:使用一台机器训练1400万张图片
  6. 读书笔记「Python编程:从入门到实践」_8.函数
  7. 【sqli-labs】 less26 GET- Error based -All you SPACES and COMMENTS belong to us(GET型基于错误的去除了空格和注释的注入)
  8. mysql中int、bigint、smallint 和 tinyint的区别与长度
  9. scrapy爬虫--10分钟入门
  10. 深度遍历DFS---树