题目
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.
解析
class Solution01 {
public void sortColors(int[] nums) {
//计数排序思路:
//创建一个数组count用来统计0,1,2出现的次数
//然后将0,1,2按顺序传值进原数组
int count[] = new int[3];
for(int n : nums){
count[n]++;
}
int index = 0;
for(int j = 0; j < 3; j++){
for(int i = 0; i < count[j] ; i++){
nums[index++] = j;
}
}
}
}

本文介绍了一种不使用库排序函数的颜色排序算法。通过计数每种颜色(0,1,2分别代表红、白、蓝)的出现次数,再将它们按顺序填入原数组的方法,实现了颜色的排序。
110

被折叠的 条评论
为什么被折叠?



