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.
记录每个颜色出现多少次就好了,然后按顺序把原数组的值改变。
1 class Solution { 2 public: 3 void sortColors(int A[], int n) { 4 int num1,num2,num3,i; 5 num1=num2=num3=0; 6 for(i=0;i<n;i++) 7 { 8 if(A[i]==0) num1++; 9 if(A[i]==1) num2++; 10 if(A[i]==2) num3++; 11 } 12 int k=0; 13 while(num1--) A[k++]=0; 14 while(num2--) A[k++]=1; 15 while(num3--) A[k++]=2; 16 } 17 };
转载于:https://www.cnblogs.com/desp/p/4345785.html
相关资源:JAVA上百实例源码以及开源项目