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