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 r = 0, w = 0; for(int i=0;i<n;i++) { if(A[i] == 0) { A[r++] = A[i]; } else if(A[i] == 1) { w++; } } for(int i=r;i<r+w;i++) { A[i] = 1; } for(int i=r+w;i<n;i++) { A[i] = 2; } } };Another in-place solution:
class Solution{ public: void sortColors(vector<int> &nums) { int red = 0; int blue = nums.size() - 1; int p = red; while(p<=blue) { if(nums[p] == 0) { if(p != red) swap(nums[red], nums[p]); else p++; red ++; } else if(nums[p] == 2) { if(p!=blue) swap(nums[blue], nums[p]); else p++; blue --; } else p++; } } };