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) { if(A==NULL ||n<=0) return; int i=0,lo=0,hi=n-1; while(i<=hi){ if (A[i]>1) swap(A[i],A[hi--]); else if(A[i]<1) swap(A[i++],A[lo++]); else i++; } } void Swap(int &a,int &b){ int temp=a; a=b; b=temp; } };
时间: 2024-10-08 10:22:49