问题描述:
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.
分析:要求对数组进行排序,但是可以看到数组是非常有特点的,即每个数不是0就是1就是2.那么就可以使用桶排序,本来桶排序还要求记录下每个桶的索引数,但是在这里也不需要了,只有记录下0有多少个,1有多少个,2有多少个即可。这样在排序的时候,只要生成足够的0,足够的1,足够的2即可。时间复杂度为O(n)
代码如下:0ms
void sortColors(int* nums, int numsSize) {
//使用桶排序
int count[3];
for(int i = 0;i<3;i++){
count[i] = 0;
}
for(int i = 0;i<numsSize;i++){
int val = nums[i];
count[val]++;
}
int numsIndex = 0;
for(int i = 0;i<3;i++){
int countt = count[i];
for(int j = 0;j<countt;j++){
nums[numsIndex++] = i;
}
}
}