当前位置:网站首页>Leetcode75. 颜色分类
Leetcode75. 颜色分类
2022-08-01 17:54:00 【Java全栈研发大联盟】
题目传送地址:https://leetcode.cn/problems/sort-colors/
运行效率
代码如下:
class Solution {
public static void sortColors(int[] nums) {
//先从左往右找到第一个2, 与此同时也要从右往左找第一个比2小的数,然后交换位置
int i = 0;
int j = nums.length - 1;
while (i < j) {
while (i < nums.length) {
if (nums[i] == 2) {
break;
}
i++;
}
while (j >= 0) {
if (nums[j] < 2) {
break;
}
j--;
}
if (i < j) {
swap(i, j, nums);
}
}
//经过上面的代码,现在所有的2都已经放到了数组的末尾了
//接下来我们对前面的0和1进行位置调整
i = 0;
j = nums.length - 1;
while (i < j) {
while (i < nums.length) {
if (nums[i] == 1) {
break;
}
i++;
}
while (j >= 0) {
if (nums[j] == 0) {
break;
}
j--;
}
if (i < j) {
swap(i, j, nums);
}
}
}
public static void swap(int i, int j, int[] nums) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
边栏推荐
猜你喜欢
How can become a good architect necessary skills: painting for all the people praise the system architecture diagram?What is the secret?Quick to open this article and have a look!.
OpenCV安装、QT、VS配置项目设置
MySQL 45 讲 | 09 普通索引和唯一索引,应该怎么选择?
食品安全 | 新鲜食品vs速食食品,哪一种是你的菜?
RecSys'22|CARCA: Cross-Attention-Aware Context and Attribute Recommendations
matlab 基于奇偶校验的LSB隐藏水印 三种改进
B005 – 基于STC8的单片机智能路灯控制系统
解决MySQL插入不了中文数据问题
面经汇总-社招-6年
QLineEdit learning and use
随机推荐
QT基础功能,信号、槽
SQL的substring_index()用法——MySQL字符串截取
缓存一致性MESI与内存屏障
加州大学|通过图抽象从不同的第三人称视频中进行逆强化学习
关于LocalDateTime的全局返回时间带“T“的时间格式处理
千万级乘客排队系统重构&压测方案总结篇
C语言:表达式求值详解
AIOps智能运维的领跑者擎创科技正式入驻InfoQ 写作社区!
变量交换;复合赋值;增递减运算符
主流小程序框架性能分析
面经汇总-社招-6年
MySQL 45 讲 | 09 普通索引和唯一索引,应该怎么选择?
中信证券是国内十大券商吗?怎么开户安全?
MySQL Lock wait timeout exceeded; try restarting transaction 锁等待
B002 - 基于嵌入式的老人定位追踪监测仪
【R语言】对图片进行裁剪 图片批量裁剪
TCP百万并发服务器优化调参
成都理工大学&电子科技大学|用于强化学习的域自适应状态表示对齐
matlab 基于奇偶校验的LSB隐藏水印 三种改进
快速抽取resnet_v2_152中间的特征层