LeetCode刷题——颜色分类

简介: 颜色分类

颜色分类


来源:力扣(LeetCode)

链接:https://leetcode.cn/problems/sort-colors


给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums ,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。

必须在不使用库的sort函数的情况下解决这个问题。


示例 1:


输入:nums = [2,0,2,1,1,0]

输出:[0,0,1,1,2,2]


示例 2:


输入:nums = [2,0,1]

输出:[0,1,2]


解答:

classSolution {
publicvoidsortColors(int[] nums) {      
intr1=-1;
intr2=-1;
for(inti=0;i<nums.length;i++){
if(nums[i] <2)
            {
r2++;
swap(nums,i,r2);
if(nums[r2] <1)
                {
r1++;
swap(nums,r1,r2);
                }
            }      
        }     
    }
voidswap(int[]nums,inti,intj)
    {
inttemp=nums[i];
nums[i] =nums[j];
nums[j] =temp;
    }
}
相关文章
|
2月前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
2月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
2月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3
|
2月前
|
容器
《LeetCode》——LeetCode刷题日记1
《LeetCode》——LeetCode刷题日记1
|
2月前
|
存储
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
144 38
|
9天前
刷题之Leetcode160题(超级详细)
刷题之Leetcode160题(超级详细)
11 0
|
9天前
刷题之Leetcode206题(超级详细)
刷题之Leetcode206题(超级详细)
21 0
刷题之Leetcode206题(超级详细)
|
9天前
|
索引
刷题之Leetcode707题(超级详细)
刷题之Leetcode707题(超级详细)
13 0
|
9天前
|
索引
刷题之Leetcode35题(超级详细)
刷题之Leetcode35题(超级详细)
13 0
|
2月前
《LeetCode》——LeetCode刷题日记2
《LeetCode》——LeetCode刷题日记2

热门文章

最新文章