75 - Sort Colors

LeetCode-75. Sort Colors (JAVA)三色排序 阅读详情

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.

click to show follow up.

Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.

Could you come up with an one-pass algorithm using only constant space?

Subscribe to see which companies asked this question

思路分析:

This is a relative easy problem.
The goal is to rearrange the array, where 0s are in the 1st part of the array, 1s in the middle, and 2s are in the    last. So, we can just scan the whole array, when meet 0, put it in the front, when meet 2, put it in the last, and leave 1 alone thus in the middle. 0 and 2's positions are stored and modified each time a swap is performed.
Details see the code.

代码如下:

class Solution {
public:
    void swap(vector<int>& nums, int i, int j)
    {
        int tmp = nums[i];
        nums[i]=nums[j];
        nums[j]=tmp;
    }

    void sortColors(vector<int>& nums) 
    {
        int red = 0;
        int blue = nums.size() - 1;
        
        while (nums[red]==0){red++;}
        while (nums[blue]==2){blue--;}
         
        int i=red;
        while (i<=blue){
            if (nums[i]==0 && i>red) {swap(nums,i,red);red++;continue;}
            if (nums[i]==2) {swap(nums,i,blue);blue--;continue;}
            i++;
        }
    }
};


南邮-软件设计实验(C++版) 南邮软件设计 A档 一、分数统计 课题内容:   设计一个分数统计程序。包括学生信息的输入输出以及排序。通过该课题全面熟悉数组、字符串、文件的使用,掌握程序设计的基本方法及友好界面的设计。 课题要求: (1)输入某班级学生的姓名、分数; (2)对(1)的分数进行降幂排列并输出; (3)具有输入输出界面。 示例代码: #include<bits/stdc++.h> using... 阅读详情

相关推荐

C语言实现俄罗斯方块

使用C语言完成俄罗斯方块。《俄罗斯方块》的基本规则是移动、旋转和摆放游戏自动输出的各种方块,使之排列成完整的一行或多行并且消除得分。由小方块组成的不同形状的板块陆续从屏幕上方落下来,玩家通过调整板块的位置和方向,使它们在屏幕底部拼出完整的一条或几条。这些完整的横条会随即消失,给新落下来的板块腾出空间,与此同时,玩家得到分数奖励。没有被消除掉的方块不断堆积起来,一旦堆到屏幕顶端,玩家便告输,游戏结束。顾名思义,俄罗斯方块自然是俄罗斯人发明的。

qq_54169998的博客 7万+

【面试题 & LeetCode 75】 Sort Colors

题目描述 Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use th...

iCode_girl的博客 312

WSL 2 部署 Rocky Linux 9:从零到生产环境配置指南(2025版)

本文详细介绍了如何在WSL 2上部署Rocky Linux 9,从环境准备到生产环境配置的全流程指南。通过优化安装流程和系统配置,帮助开发者和运维工程师在Windows环境下高效运行企业级Linux系统,特别适合需要本地开发但部署到RHEL系服务器的项目。

weixin_28455801的博客 479

LeetCode-75 Sort Colors

Description Given an array nums with n objects colored red, white, or blue, sort them in-place 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 co

秦智慧的博客 195

2.1 量子精密测量:SERF原子陀螺仪中的核自旋-电子自旋强耦合机制

本文深入解析了SERF原子陀螺仪中核自旋-电子自旋强耦合机制的核心原理与应用。通过量子精密测量技术,SERF陀螺仪实现了超高精度的惯性导航,其独特的磁场自补偿和拉莫尔进动特性使其在弱磁场环境下表现出色。文章还探讨了关键技术突破和前沿进展,展示了量子精密测量在惯性导航领域的巨大潜力。

kotlin6android的博客 212

别再凭感觉了!手把手教你用Excel搞定激光器MPE与NOHD安全计算(附模板下载)

本文详细介绍了如何利用Excel自动化计算激光器的MPE(最大允许照射量)和NOHD(标称眼危害距离),提升激光安全评估的效率和准确性。通过实战案例和模板下载,帮助工程师快速掌握GB/T 7247标准中的关键计算,避免常见错误,适用于激光测距仪等设备的安评工作。

weixin_30954265的博客 468

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 int...

weixin_33787529的博客 184

告别手动复制粘贴:3种高效合并Excel表格的方法对比(含代码)

本文对比了VBA、Power Query和Python三种高效合并Excel表格的方法,并提供了可直接运行的代码。针对不同数据量、更新频率和技术背景,详细分析了各方案的优缺点与适用场景,帮助读者告别低效的手动操作,实现自动化数据整合。

weixin_29057237的博客 445

【LeetCode】对数组中的不同颜色进行排序,使得相同颜色相邻: Sort Colors

Given an array withnobjects colored red, white or blue, sort themin-placeso 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, an...

Arlingtonroad的博客 569

高等数学/概率论/数理统计/线性代数/离散数学面试-核心概念-问题理解

特征值与特征向量是线性代数中的概念,它们与线性变换有关。在线性变换中,如果存在非零向量 v ,使得当该向量通过变换后,其方向不变,只是长度发生了变化,那么这个向量 v 就是特征向量。而这个长度变化的比例因子,即变换前后向量长度的比值,称为特征值。数学公式表示:通俗易懂的解释:想象一下,你有一个可以伸缩的橡皮筋,这个橡皮筋可以代表一个向量。现在,你有一个特殊的机器,它可以改变橡皮筋的形状,但不会改变它延伸的方向。当你把橡皮筋放入机器中,机器会拉伸或压缩橡皮筋,但橡皮筋的方向保持不变。

m0_64198455的博客 2294

Flutter连接蓝牙打印机打印(含中文、双排打印)

Flutter连接蓝牙打印机打印(含中文、双排打印)

Session_W的博客 701

75. Sort Colors

75.Sort Colors Medium 5164296Add to ListShare Given an arraynumswithnobjects colored red, white, or blue, sort themin-placeso that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integer...

Sterben_Da的博客 186

手把手教你用U盘制作Win11启动盘:从PE工具到系统安装全流程

本文提供了一份详尽的Windows 11启动盘制作与系统安装全流程指南。从选择合适的U盘和PE工具开始,重点讲解了如何正确制作包含EFI引导分区的启动盘,并详细演示了在PE环境下进行GPT分区、使用CGI工具安装系统镜像,以及首次启动后的关键设置步骤,帮助用户轻松完成从零到一的系统安装。

weixin_28475533的博客 1295

leetcode75. Sort Colors

75. Sort Colors 帅气 class Solution { public void sortColors(int[] nums) { int zero =0; int two = nums.length -1; int i =0; while(i<nums.length){ while...

日暮图远8102的博客 167

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

【LeetCode】解题75:Sort Colors

LeetCode解题 75:Sort Colors Problem 75: Sort Colors [Medium]解题思路Solution (Java)修改过程 Problem 75: Sort Colors [Medium] Given an array with n objects colored red, white or blue, sort them in-place so that ...

Fayedily的博客 269

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

75. Sort Colors**

75. Sort Colors** https://leetcode.com/problems/sort-colors/ 题目描述 Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the ...

珍妮的选择的博客 215

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

[LeetCode]75. Sort Colors

[LeetCode]75. Sort Colors题目描述思路只有三个数字,可以用快排简化版,确定支点为1 进一步,更简单的方法,扫描一次获取每个数字的个数即可代码class Solution { public: void sortColors(vector<int>& nums) { int count_0 = 0, count_1 = 0; for (i

Lcharon的博客 2410

LeetCode 75. Sort Colors--Python解法

LeetCode题解专栏:LeetCode题解 我做的所有的LeetCode的题目都放在这个专栏里,大部分题目Java和Python的解法都有。 题目地址:Sort Colors - LeetCode Given an array with n objects colored red, white or blue, sort them in-place so that objects of ...

个人博客 522

leetcode-75-sort colors

问题题目:[leetcode-75-sort colors]思路以下思路参考[算法系列之十一荷兰国旗问题] 我们可以把数组分成三部分,前部(全部是0),中部(全部是1)和后部(全部是2)三个部分,每一个元素(红白蓝分别对应0、1、2)必属于其中之一。 将前部和后部各排在数组的前边和后边,中部自然就排好了。 设置两个指针begin指向前部的末尾的下一个元素(刚开始默认前部无0,

Kang_TJU的博客 608

LeetCode 75. Sort Colors 题解

本题是排序算法的经典应用问题,主要考察对三指针排序方法的理解和使用。通过使用三个指针,我们可以高效地对包含0、1、2的数组进行排序。三指针的核心思想是:使用三个指针分别指向0的右边界、2的左边界和当前处理的元素,根据当前元素的值进行相应的交换和指针移动。这种方法不仅适用于颜色排序问题,还可以应用于许多其他需要对有限种类元素进行排序的问题。掌握三指针的使用,对于解决这类问题非常重要。

cannonjinx的博客 4286

LeetCode 75. Sort Colors

LeetCode 75. Sort Colors Description 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

Vimer.Bai的博客 241

Leetcode 75 Sort Colors

Leetcode 75 Sort Colors Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. H...

herosunly的博客 1万+

【Leetcode】75. 排序颜色(Sort Colors)

Leetcode - 75 Sort Colors (Medium) 题目描述:0、1、2 分别代表三种颜色,给定由这三个数组组成的数组,将数组内的元素按照 0、1、2 的顺序排列。 Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2] public void sortColors(int[] nums) { int zero = -1, one = 0,...

厉兵秣码 396

Leetcode 75. Sort Colors

Leetcode 75. Sort Colors class Solution { public: void sortColors(vector&amp;lt;int&amp;gt;&amp;amp; nums) { int size = nums.size(); if(size &amp;lt;= 1) return; for(int i = 0;i &amp;lt; size; ...

自己的学习笔记 195
上一篇: 74 - Search a 2D Matrix
下一篇: 80 - Remove Duplicates from Sorted Array II
hellochenlu
博客等级 码龄14年 97粉丝 184原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值