Title:

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.

直观的解法是使用计数排序

class Solution {
public:
void sortColors(vector<int>& nums) {
int *c = new int [];
memset(c,,sizeof(int)*);
for (int i = ; i < nums.size(); i++){
c[nums[i]]++;
}
nums.clear();
for (int i = ; i < ; i++){
for (int j = ; j < c[i]; j++){
nums.push_back(i);
}
}
}
};

也可以遍历一次就能得到结果,使用3个下标,分别指向0,1,2对应的下标位置。可以这么理解,最左边是0,最右边是2,中间遇到1不用管

class Solution {
public:
void sortColors(int A[], int n) {
if(n <= ) return;
int start = -, end = n;
int p = ;
while(p < n && start < end){
if(A[p] == ){
if(p > start) swap(A, ++start, p);
}else if(A[p] == ){
if(p < end) swap(A, p, --end);
}else ++p;
}
}
private:
void swap(int A[], int i, int j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
};

最新文章

  1. c#使用多线程的几种方式示例详解
  2. day22、模块-basedir、os、json模块、pickle和正则模块。
  3. 微信公众平台开发(68)苹果IMEI查询
  4. Spring shiro使用
  5. 各式 Web 前端開發工具整理
  6. 如何搭建一个angularJS应用
  7. jQuery UI Widget(1.8.1)工作原理--转载
  8. 使用javaservice 将jboss 注册为服务
  9. 不安装oracle客户端,如何运行sqlplus
  10. YII 框架在 MAC OS下 连接数据库失败 提示 DB connection: SQLSTATE[HY000] [2002]
  11. SQL 数据库基本知识
  12. bzoj1834 [ZJOI2010]网络扩容
  13. Web框架django[Form]组件
  14. ONCOCNV软件思路分析之control处理
  15. ES2018新特性(译文)
  16. Batch入门教程丨第一章:部署与Hello World!(上)
  17. 什么是javabean及其用法(转)
  18. Thing in java 第5章,初始化和清理,练习题答案
  19. ==,hashcde, equals(一)
  20. Js高级 事件 对象

热门文章

  1. js收集的一些好的题型
  2. 如何通过css控制内容显示顺序 第二行的内容优先显示
  3. Unity3d修改FBX文件的动画名方法
  4. POJ1860Currency Exchange(SPFA)
  5. hdu 4497 GCD and LCM
  6. C# 计算一段代码执行的时间函数
  7. 使用CXF与Spring集成实现RESTFul WebService
  8. SaaS系列介绍之十四: SaaS软件开发分析
  9. 【mongoDB运维篇②】备份与恢复(导入与导出)
  10. SpringMVC学习总结(三)——Controller接口详解(1)