算法—數組:荷蘭國旗問題

tips:本文章內容來自《程序員編程藝術:面試和算法心得》

給定一個字符串里面只有"R" "G" "B" 三個字符,請排序,最終結果的順序是R在前 G中 B在后。
要求:空間復雜度是O(1),且只能遍歷一次字符串。

只是需要用到三個指針:一個前指針begin,一個中指針current,一個后指針end,current指針遍歷整個數組序列,當

current指針所指元素為0時,與begin指針所指的元素交換,而后current++,begin++ ;

current指針所指元素為1時,不做任何交換(即球不動),而后current++ ;

current指針所指元素為2時,與end指針所指的元素交換,而后,current指針不動,end-- 。


參考代碼:

/**

*荷蘭國旗問題

*/

void helanguoqi (char* str,unsigned long length){

? ? ? if(NULL== str || 0== length)

? ? ? ? ? ? ? ? return;

? ? ? char* strBegin = str;

? ? ? char* strCurrent = str;

? ? ? char* strEnd = str+length-1;

? ? ? while(strCurrent < strEnd) {

? ? ? ? ? ? ? if('R' == *strCurrent) {

? ? ? ? ? ? ? ? ? ?swap(*strBegin, *strCurrent);

? ? ? ? ? ? ? ? ? ?strBegin++;

? ? ? ? ? ? ? ? ? ?strCurrent++;//仔細想想為什么這里可以++

? ? ? ? ? ? ? ?}elseif('G' == *strCurrent){

? ? ? ? ? ? ? ? ? ? ? ? strCurrent++;

? ? ? ? ? ? ? ?}else{?

? ? ? ? ? ? ? ? ? ? ? ? swap(*strCurrent, *strEnd);

? ? ? ? ? ? ? ? ? ? ? ? strEnd--;

?}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容