问题:把 3种颜色(0,1,2)在一个数组里,每次只可交换一次,扫描一边后,三种颜色自然分开,应为颜色为:红,白,蓝,(荷兰国旗的颜色)所也叫荷兰国旗问题! 代码: #include <stdlib.h> #include <iostream.h> int main() { int a[10]; for( int i=0 ; i<10 ; i++ ) { a[i] = rand() % 3; cout<<a[i]<<' '; } cout<<endl; int first = 0; int end = 9; int mem = 0; while( first <= end ) { if( a[first] == 0 ) { int temp = a[first]; a[first] = a[mem]; a[mem] = temp; mem++; first++; } else if( a[first] == 1 ) { first++; } else if( a[first] == 2 ) { int temp = a[first]; a[first] = a[end]; a[end] = temp; end--; } } return 0;} PS:这个解决办法是O(n)的!