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.
统计数量然后直接赋值,过掉这道题的方法有点无赖。。。
class Solution {
public:
void sortColors(int A[], int n) {
int num0=0, num1=0, num2=0;
for (int i=0; i<n; i++) {
switch (A[i]) {
case 0: num0++; break;
case 1: num1++; break;
case 2: num2++; break;
}
}
for (int i=0; i<n; i++) {
if (i<num0) A[i] = 0;
else if (i<num1+num0) A[i] = 1;
else A[i] = 2;
}
}
};