题目:
Sort Colors
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.
从头到尾遍历数组,将0放到前面,将2放到后面,i所在的元素保证不为0也不为2,才i++。
class Solution {
public:
void sortColors(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int p0=0, p2=n-1;
int i = 0;
for (i=0; i<=p2; i++)
{
if(A[i]==0)
{
A[i]=A[p0];
A[p0++]=0;
}
else if(A[i]==2)
{
A[i]=A[p2];
A[p2--]=2;
i--;
}
}
}
};