当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢

实现mnist手写数字识别

数字化采购管理系统开发:精细化采购业务流程管理,赋能企业实现“阳光采购”

MySql 怎么查出符合条件的最新的数据行?

浅谈游戏音效测试点

广汽埃安“弹匣电池”,四大核心技术,出行安全保障

Unity ui点击事件只响应最上层ui的方式

B011 - 51-based multifunctional fingerprint smart lock

QPalette palette, frame color fill

XAML WPF item groupBox control

【报错】Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘concat‘)
随机推荐
浅谈游戏音效测试点
解决MySQL插入不了中文数据问题
创造建材数字转型新视界,中建材如何多边赋能集团业务快速发展
Review实战经典:2 种封装风格,你偏爱哪种?
主流小程序框架性能分析
Solve the problem that MySQL cannot insert Chinese data
【Error】Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘concat’)
半自动化爬虫-爬取一个网站的内容及回复
Xingtu has been short of disruptive products?Will this M38T from the Qingdao factory be a breakthrough?
typora操作手册
阿里云的域名和ip绑定
QPalette调色板、框架色彩填充
云商店携手快报税,解锁财务服务新体验!
QT常用全局宏定义
理财产品的月年化收益率怎么算?
MySQL Lock wait timeout exceeded; try restarting transaction 锁等待
SQL的substring_index()用法——MySQL字符串截取
M1芯片电脑安装cerebro
开发工具:第五章:使用idea生成实体类
C语言:表达式求值详解