首页 技术 正文
技术 2022年11月14日
0 收藏 998 点赞 4,697 浏览 1177 个字

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?

解1 计数排序

 class Solution {
public:
void sortColors(vector<int>& v) {
vector<int> count(, ); for (int i = ; i < v.size(); ++i) {
if (v[i] == ) {
++count[];
} else if (v[i] == ) {
++count[];
} else {
++count[];
}
} int it = ;
for (int i = ; i < ; ++i) {
for (int j = ; j < count[i]; ++j) {
v[it++] = i;
}
}
}
};

解2 双指针思想的延伸

 class Solution {
public:
void sortColors(vector<int>& v) {
int low = , mid = , high = v.size() - ;
while (mid <= high) {
if (v[mid] == ) {
swap(v[mid], v[low]);
++low;
++mid;
} else if (v[mid] == ) {
swap(v[mid], v[high]);
--high;
} else {
++mid;
}
}
}
};

解3 比较有技巧

 class Solution {
public:
void sortColors(vector<int>& v) {
int n0 = -, n1 = -, n2 = -; for (int i = ; i < v.size(); ++i) {
if (v[i] == ) {
v[++n2] = ;
v[++n1] = ;
v[++n0] = ;
} else if (v[i] == ) {
v[++n2] = ;
v[++n1] = ;
} else {
v[++n2] = ;
}
}
}
};
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,487
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,486
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,126
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,287