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.
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?
这道题最简单的方法就是采用计数排序,然后对原数组重新赋值,没什么难度,代码如下:
/*solution1 4ms use counting sort*/
class Solution {
public:
void sortColors(vector<int>& nums) {
int i=0,j=0,k=0;
vector<int> zero;
vector<int> one;
vector<int> two;
for(i=0;i<nums.size();i++){
switch(nums[i]){
case 0:
zero.push_back(nums[i]);
break;
case 1:
one.push_back(nums[i]);
break;
case 2:
two.push_back(nums[i]);
break;
}
}
for(i=0;i<zero.size();i++)
nums[i]=zero[i];
for(i,j=0;j<one.size();i++,j++)
nums[i]=one[j];
for(i,k=0;k<two.size();i++,k++)
nums[i]=two[k];
}
};
不过这个解法并不能算作完美的算法,因为申请了额外的空间,并且进行了多次的遍历。
现在考虑能不能用恒定的空间和one-pass来解决问题,考虑到只有三种元素,0 1 2,那么我们可以借鉴快排的思路,以1为pivot,然后把0放在1左边,2在1右边,这是大致的思路。
要实现这个算法,我们需要三个指针,low high和cur,其中low,high分别指向0和2组成的序列的边界,cur从最左端开始向后遍历,那么有以下几种情况:
- nums[cur]==0 应该将其与low指向的元素交换,因为nums[low]始终 ==1或low ==cur,所以交换后的nums[cur]已经到位,只需cur++,low++
- nums[cur]==1 已经就位,cur++即可
- nums[cur]==2 应该将其与high指向的元素作交换,但是high指向的元素的值不确定,所以只能让high–,cur不变
下面以一个数组为例进行演示
1 0 2 2 1 0
^ ^
L H
M
Mid != 0 || 2
Mid++
1 0 2 2 1 0
^ ^ ^
L M H
Mid == 0
Swap Low and Mid
Mid++
Low++
0 1 2 2 1 0
^ ^ ^
L M H
Mid == 2
Swap High and Mid
High--
0 1 0 2 1 2
^ ^ ^
L M H
Mid == 0
Swap Low and Mid
Mid++
Low++
0 0 1 2 1 2
^ ^ ^
L M H
Mid == 2
Swap High and Mid
High--
0 0 1 1 2 2
^ ^
L M
H
由此可见,循环条件应该是mid<=high
代码如下:
class Solution {
public:
void sortColors(vector<int>& nums) {
int low=0,high=nums.size()-1,cur=0;
while(cur<=high){
if(nums[cur]==0)
swap(nums[cur++],nums[low++]);
else if(nums[cur]==1)
cur++;
else if(nums[cur]==2)
swap(nums[cur],nums[high--]);
}
}
};