# Sort Colors

Oct 19, 2017

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.

• 遍历待排数组，记录元素出现的次数
• 通过元素出现的次数，修改待排数组
void sortColors(vector<int>& nums) {
vector<int> count(3,0);

for(auto i:nums)
count[i]++;

int i = 0,k = 0;
while(k < nums.size()) {
while (count[i] == 0) i++;
nums[k] = i;
k++;
count[i]--;
}
}


void sortColors(int A[], int n) {
int second=n-1, zero=0;
for (int i=0; i<=second; i++) {
while (A[i]==2 && i<second) swap(A[i], A[second--]);
while (A[i]==0 && i>zero) swap(A[i], A[zero++]);
}
}

LeetCodeLeetCodesort

Subsets

Unique Paths