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.
本题改进的地方:
注释了 j = j-1;
并在后面加上了while(a[j]==1||a[j]==2)j--;
主要原因是, 有可能没有2的时候, j就不能从j-1的地方开始了
class Solution { public: void swap(int& a, int& b) { int temp = a; a = b; b = temp; } void sortColors(int A[], int n) { if(n==0) return; int i = 0, j = n-1; for(;i<j;) { while(A[j]==2)j--; while(A[i]==0||A[i]==1)i++; if(i<j) swap(A[i],A[j]); } i = 0; //j = j-1; for(;i<j;) { while(A[j]==1||A[j]==2)j--; while(A[i]==0)i++; if(i<j) swap(A[i],A[j]); } } };