题目:Sort color

<span style="font-size:18px;">/*LeetCode sort colors
题目:输入一个数组。包括0,1,2分别代表红白蓝三种颜色,要求依照0,1,2的顺序,将同类颜色的连续排列
思路:计数排序,是一个遍历两遍的方法:能够先统计每种的数量,之后直接将这一范围内的全部值都赋值为对应的数字就可以
遍历一遍的话能够在遍历的同一时候分别与0和2比較,从头和尾一起交换。1的在中间不用做处理;
*
*/
package javaTrain; public class Train13 {
public void sortColors(int[] A) {
int n = A.length;
int red = 0,blue = n-1; for(int i=0;i < blue+1;){ //由于会从后向前推进所以以blue表示尾部,确保仅仅用遍历一遍
int temp = A[i];
if(temp == 0){
A[i++] = A[red]; //由于red在前。所以交换时它指向的仅仅能是0或1。所以交换后的位置能够向前移
A[red++] = temp;
}
else if(temp == 2){
A[i] = A[blue]; //而blue在后。它指向的之前并没有被比較过有可能有0,1,2所以交换的点不能向前移
A[blue--] = temp;
}
}
}
}
</span>

最新文章

  1. iOS 取绝对值函数
  2. apache和tomcat有什么不同,为什么要整合apache 和tomcat?
  3. LeetCode Rotate List (链表操作)
  4. SQL Server XML Path[转]
  5. BZOJ 1974: [Sdoi2010]auction 代码拍卖会( dp )
  6. 编写可维护的JavaScript—语句和表达式&amp;变量、函数和运算符
  7. Linux 下开启ssh服务
  8. 第一个ExtJS练习(添加用户面板)
  9. TCP/IP四层模型与OSI参考模型
  10. html5的八大特性
  11. Spring Boot 引入org.springframework.boot.SpringApplication出错
  12. springcoud feign超时的问题
  13. [Leetcode 104]求二叉树的深度Depth of BinaryTree
  14. 回调函数ros::spin()与ros::spinOnce()
  15. 文件上传submit、ajax方式
  16. HTML5动感圆圈
  17. python拓展应用:运行do文件及其衍生内容
  18. c# mysql blob数据类型
  19. pat1057. Stack (30)
  20. iperf3

热门文章

  1. 数据库函数:sqlite3_exec() SQL语句
  2. source insight setting
  3. 一个boost底下的线程池
  4. Appium+python自动化19-iOS模拟器(iOS Simulator)安装自家APP【转载】
  5. pandas read excel文件碰到的一个小问题
  6. App接口加密解密方法
  7. UbuntuMate开机自动启动ssh服务
  8. json model 互转
  9. struts2进阶
  10. 利用MAP动态创建C++类对象