当前位置:网站首页>Leetcode75. Color Classification
Leetcode75. Color Classification
2022-08-01 17:58:00 【Java Full Stack R&D Alliance】
题目传送地址:https://leetcode.cn/problems/sort-colors/
运行效率
代码如下:
class Solution {
public static void sortColors(int[] nums) {
//Find the first one from left to right2, At the same time, look for the first ratio from right to left2小的数,然后交换位置
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);
}
}
//经过上面的代码,现在所有的2have been placed at the end of the array
//Next, we will0和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;
}
}
边栏推荐
猜你喜欢

8月微软技术课程,欢迎参与

【Day_09 0427】走方格的方案数

TCP million concurrent server optimization parameters

RecSys'22|CARCA: Cross-Attention-Aware Context and Attribute Recommendations

缓存一致性MESI与内存屏障

QT commonly used global macro definitions

B005 – 基于STC8的单片机智能路灯控制系统

Detailed explanation of the working principle of crystal oscillator

ROS2支持技术:DDS简述

统信软件、龙芯中科等四家企业共同发布《数字办公安全创新方案》
随机推荐
成为优秀架构师必备技能:怎样才能画出让所有人赞不绝口的系统架构图?秘诀是什么?快来打开这篇文章看看吧!...
md5sum源码 可多平台编译
机器学习快速入门
B011 - 51-based multifunctional fingerprint smart lock
ROS2系列知识(6):Action服务概念
SQL函数 TO_CHAR(三)
半自动化爬虫-爬取一个网站的内容及回复
gtk显示4通道rgba图像
Topology零部件拆解3D可视化解决方案
Basic image processing in opencv
CodeTON Round 2 (Div. 1 + Div. 2, Rated, Prizes!) 题解
QT_QDialog 对话框
实现mnist手写数字识别
公用函数----mfc
matlab 基于奇偶校验的LSB隐藏水印 三种改进
B001 - Intelligent ecological fish tank based on STM32
变量交换;复合赋值;增递减运算符
Xingtu has been short of disruptive products?Will this M38T from the Qingdao factory be a breakthrough?
2022年SQL大厂高频实战面试题(详细解析)
RecSys'22|CARCA:交叉注意力感知上下文和属性进行推荐