当前位置:网站首页>75. 颜色分类
75. 颜色分类
2022-07-30 05:15:00 【Alex_Drag】
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
注意:
不能使用代码库中的排序函数来解决这道题。
示例:
输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]
进阶:
一个直观的解决方案是使用计数排序的两趟扫描算法。
首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
你能想出一个仅使用常数空间的一趟扫描算法吗?
使用三指针,用zero来记录第一个不为0的位置,用two记录最小的不为2的位置,用cur来遍历整个数组。
public void sortColors(int[] nums) {
int zero = 0;
int two = nums.length - 1;
int cur = 0;
while(cur <= two) {
if(nums[cur] == 0)
swap(nums, zero++, cur);
else if (nums[cur] == 2)
swap(nums, cur--, two--);
cur++;
}
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-colors
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
边栏推荐
- Internet (software) company project management software research report
- Let's talk about what SaaS is, and the problems encountered...
- C language implements highly secure game archives and reads files
- 【Vitis】ZCU102开发板PS端控制PL端复位的代码实现
- 开源之夏 2022 与您相约!
- 力扣05-替换空格——字符串问题
- LeetCode Algorithm 2326. Spiral Matrix IV
- IGBT wafers used in photovoltaic inverters
- go language study notes 2
- 如何让 (a == 1 && a == 2 && a == 3) 的值为true?
猜你喜欢
随机推荐
ThinkPHP高仿蓝奏云网盘系统源码/对接易支付系统程序
给小白的 PG 容器化部署教程(下)
从字节码角度带你彻底理解异常中catch,return和finally,再也不用死记硬背了
Divide and conquer. L2-025
文档在线化管理系统Confluce使用
NFT 产品设计路线图
为Bitbucket 和 Sourcetree 设置SSL认证
力扣1047-删除字符串中的所有相邻重复项——栈
容器化 | 在 K8s 上部署 RadonDB MySQL Operator 和集群
Dynamically bind href url
Small programs use npm packages to customize global styles
丑陋的程序员
How can I make (a == 1 && a == 2 && a == 3) to be true?
pytorch官网中如何选择以及后面的安装和pycharm测试步骤
【LeetCode】Day107-除自身以外数组的乘积
Hexagon_V65_Programmers_Reference_Manual (14)
mysql基础(4)
RadonDB MySQL on K8s 2.1.2 发布!
[3D Detection Series-PointRCNN] Reproduces the PointRCNN code, and realizes the visualization of PointRCNN3D target detection, including the download link of pre-training weights (starting from 0 and
Internet (software) company project management software research report









