Fork me on GitHub

[leetcode-75-Sort Colors]

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent,
with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library's sort function for this problem.

思路:

首先扫描一遍,统计不同元素个数。

类似于two pointers概念。

复制代码
void sortColors(vector<int>& nums)
     {
         if (nums.size() <= 1)return;
         vector<int>temp = nums;
         int zero = 0, one = 0, two = 0, index0 = 0, index1 = 0, index2 = 0;
         for (int i = 0; i < nums.size();i++)
         {
             if (nums[i] == 0)zero++;
             if (nums[i] == 1)one++;
             if (nums[i] == 2)two++;             
         }
         index1 = zero, index2 = zero + one;
         for (int i = 0; i < temp.size(); i++)
         {
             if (temp[i] == 0)nums[index0++] = 0;
             if (temp[i] == 1)nums[index1++] = 1;
             if (temp[i] == 2)nums[index2++] = 2;
         }
     }
复制代码

 

posted @   hellowOOOrld  阅读(138)  评论(0编辑  收藏  举报
编辑推荐:
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
阅读排行:
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Browser-use 详细介绍&使用文档
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞
点击右上角即可分享
微信分享提示