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 }

 

相关文章:

  • 2021-08-21
  • 2022-03-02
  • 2021-10-12
  • 2021-05-27
猜你喜欢
  • 2021-10-01
  • 2022-03-09
  • 2022-01-19
  • 2021-12-23
相关资源
相似解决方案