class Solution {
public:
void sortColors(vector<int>& nums) {
if (nums.size() == 0) {
return;
}
int N = nums.size(), index = 0;
vector<int> cnt(3, 0);
for (int i = 0; i < N; i++) {
cnt[nums[i]]++;
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < cnt[i]; j++) {
nums[index++] = i;
}
}
}
};
方法2
class Solution {
public:
void sortColors(vector<int>& nums) {
int red = 0;
int blue = nums.size() - 1;
for (int i = 0; i <= blue; i++) {
if (nums[i] == 0) {
swap(nums, i, red++);
} else if (nums[i] == 2) {
swap(nums, i, blue--);
}
}
}
private:
void swap(vector<int>& nums, int a, int b) {
int tmp = nums[a];
nums[a] = nums[b];
nums[b] = tmp;
}
};