当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢
后台管理系统的权限思路
创造建材数字转型新视界,中建材如何多边赋能集团业务快速发展
MySQL Lock wait timeout exceeded; try restarting transaction 锁等待
Xingtu has been short of disruptive products?Will this M38T from the Qingdao factory be a breakthrough?
SQL窗口函数
分布式消息队列平滑迁移技术实战
B011 - 基于51的多功能指纹智能锁
【Day_10 0428】井字棋
QT basic functions, signals, slots
今年最火爆的词:商业分析,看这一篇就够了!
随机推荐
[供应链·案例篇]石油和天然气行业的数字化转型用例
【Day_12 0507】二进制插入
typora操作手册
后台管理系统的权限思路
解决MySQL插入不了中文数据问题
百度网盘下载速度提升100倍
棕榈油罐区数字化转型
食品安全 | 新鲜食品vs速食食品,哪一种是你的菜?
B005 – 基于STC8的单片机智能路灯控制系统
2022年SQL经典面试题总结(带解析)
sql添加索引
C语言理论--笔试面试基础稳固
频域分析实践介绍
理财产品的月年化收益率怎么算?
力扣每日一题-第45天-697. 数组的度
2022年MySQL最新面试题
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!.
AIOps智能运维的领跑者擎创科技正式入驻InfoQ 写作社区!
opencv语法Mat类型总结
opencv实时人脸检测