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.
class Solution { //计数排序 public: void sortColors(vector<int>& nums) { int k0=0; int k1=0; int k2=0; for(int i=0;i<nums.size();i++) { if(nums[i]==0) k0++; else if(nums[i]==1) k1++; else k2++; } for(int i=0;i<nums.size();i++) { if(i<k0) nums[i]=0; else if(i<(k0+k1)) nums[i]=1; else nums[i]=2; } } };
原文:http://blog.csdn.net/u011391629/article/details/52122521