博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode - Sort Colors
阅读量:7036 次
发布时间:2019-06-28

本文共 958 字,大约阅读时间需要 3 分钟。

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.

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?

class Solution {public:    void sortColors(int A[], int n) {        int r = 0,w = 0,b = 0;		for (int i = 0; i < n; i++)		{			if(A[i] == 0) r += 1;			if(A[i] == 1) w += 1;			if(A[i] == 2) b += 1;		}		for (int i = 0; i < n; i++)		{			A[i] = i < r ? 0 : (i < r + w ? 1 : 2);		}    }};

版权声明:本文博客原创文章,博客,未经同意,不得转载。

你可能感兴趣的文章
2012年度IT博客大赛50强报道:桂素伟
查看>>
女程序员的职业规划
查看>>
我的友情链接
查看>>
ExchangeApplicationPool意外停止--OWA異常
查看>>
System Center Data Protection Manager 2010 部署指南
查看>>
Tomcat指定(JDK路径)JAVA_HOME而不用环境变量
查看>>
python+selenium+PIL+tesseract验证码识别
查看>>
请教一个问题:关于 webrtc 通信的问题
查看>>
xtrabackup自动还原v2
查看>>
偶遇问题之ORA-07445 ORA-00108 报错处理
查看>>
zabbix微信报警
查看>>
ubuntu安装拼音输入法
查看>>
杂乱笔记—GRE over IPsec ***
查看>>
linux负载监控
查看>>
Python学习小记(1)—命令指示符
查看>>
lnmp一键安装之-php
查看>>
ajax 同步和异步的区别
查看>>
linux shell单引号、双引号及无引号区别(考试题答案系列)--看到这篇文章之后我豁然开朗...
查看>>
排错 zabbix-agent 主机重启无法被监控
查看>>
win10操作系统
查看>>