sort color

sort color

easy probem count sorting

because the range of keys is limited, so count sorting is the best way.

 1 class Solution {
 2 public:
 3     void sortColors(int A[], int n) {
 4         int color[3];
 5         memset(color,0,sizeof(color));
 6         for ( int i = 0; i < n; i++ ) {
 7             color[A[i]]++;
 8         }
 9         int k = 0;
10         for ( int i = 0; i < 3; i++ ) {
11             for ( int j = 0; j < color[i]; j++ ) {
12                 A[k++] = i;
13             }
14         }
15     }
16 };

Loading Disqus comments...
Table of Contents