zoukankan      html  css  js  c++  java
  • 75. 颜色分类

    给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。

    此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。

    注意:
    不能使用代码库中的排序函数来解决这道题。

    示例:

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

    进阶:

    一个直观的解决方案是使用计数排序的两趟扫描算法。

    首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。

    你能想出一个仅使用常数空间的一趟扫描算法吗?

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/sort-colors
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    Code

    class Solution {
    public:
        void sortColors(vector<int>& nums) {
            auto index = nums.begin();
            auto less = nums.begin();
            auto more = nums.end();
            less--;
    
            while (index < more){
                if (*index == 0){
                    less++;
                    swap(*less,*index);
                    index++;
                } else if (*index == 1){
                    index++;
                } else if (*index == 2){
                    more--;
                    swap(*more,*index);
                }
            }
        }
    };
    
  • 相关阅读:
    输入输出,数据类型,运算符
    queue与pair
    迪杰斯特拉算法学习
    IP地址/数字表示学习
    作业与进程的关系
    直写和回写学习
    OS中的时空局部性
    scanpy包的预处理函数学习
    keras编译与训练过程
    力扣:前缀和、差分题目
  • 原文地址:https://www.cnblogs.com/AlexKing007/p/12338100.html
Copyright © 2011-2022 走看看