class Solution {
public:
void sortColors(vector<int>& nums) {
int s[3] = {0,0,0};
for (int i = 0; i < nums.size(); i++) {
if (nums[i] == 0) {
nums[s[2]++] = 2;
nums[s[1]++] = 1;
nums[s[0]++] = 0;
} else if (nums[i] == 1) {
nums[s[2]++] = 2;
nums[s[1]++] = 1;
} else {
nums[s[2]++] = 2;
}
}
}
};
Share my one loop C++ solution


s[0] stands for the next position of last 0 in the sorted part, so does s[1] and s[2]. Before insert a number into the sorted part, you should have a space for it. So when you insert 0 you should move the part of 1s and 2s back one step. Then you can insert 0 to replace the first 1 where is next to the last 0 in the sorted part. There is an example:1 2 2 2 0 (1 2 2 2 is sorted part)=====> 1 2 2 2 2 =====> 1 1 2 2 2 =====> 0 1 2 2 2