LeeCode-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.

 

 1 void sortColors(int* nums, int numsSize)
 2 {
 3         if(numsSize==0||nums==NULL)
 4         return;
 5 
 6     if(numsSize==1)
 7         return;
 8 
 9     int red=0,white=0,blue=0;
10 
11     for(int i=0;i<numsSize;i++)
12     {
13         if(nums[i]==0)
14             red++;
15 
16         if(nums[i]==1)
17             white++;
18 
19         if(nums[i]==2)
20             blue++;
21     }
22     for(int i=0;i<numsSize;i++)
23     {
24         if(i<red)
25         {
26             nums[i]=0;
27         }
28         if(i>=red&&i<(red+white))
29         {
30             nums[i]=1;
31         }
32         if(i>=(red+white)&&i<numsSize)
33         {
34             nums[i]=2;
35         }
36 
37     }
38 }

 

你可能感兴趣的:(color)