每日一题系列 - 荷兰国旗问题
『每日一題』
題目取自清華大學《數據結構》題集,嚴蔚敏,米寧, 吳偉民
?
荷蘭國旗問題:(難度5)設有一個僅由紅白藍三種顏色的條塊組成的條塊序列。求一種時間復雜度O(n)的算法,使得這些條塊按紅、白、藍的順序排好,即排成荷蘭國旗的圖案。
?
分析:大意是比如{紅,藍,白,白,藍,紅,白,藍,白} -->{紅,紅,藍,藍,藍,白,白,白,白}的調整
不過該題目并未規定是否可以另辟存儲空間。
?
有興趣的試試看吧。
?
『題解』:
其實此題并不難,如果一開始沒有思路,可以先降級考慮一下兩色旗問題,相信可以很快用分別指向隊頭和隊尾兩個的指針平行移動來調整序列內元素,算法復雜度是O(n)。然后考慮多了一種顏色,就是加了一個指針而已,算法復雜度不受影響。
?
該實現不用另辟array空間。需要額外幾個指針。
?
//參數說明:red, current 指向隊頭,white指向隊尾 void threeFlag(int* red, int * current, int * white) {while(current!=white){if(*current==0){if(current==red){current++;red++;continue;}if(current>red){int temp;temp=*red;*red=*current;*current=temp;red++;continue;}}if(*current==1){current++;continue;}if(*current==2){if(*white==2){white--;continue;}int temp;temp=*current;*current=*white;*white=temp;continue;}} } //testing scripts //0=red flag; 1=blue flag; 2=whiteint flags[12] ={0,1,2,1,0,2,1,2,1,1,1,0};cout<<flags;threeFlag(flags,flags,flags+11);cout<<flags;
?
總結
以上是生活随笔為你收集整理的每日一题系列 - 荷兰国旗问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: myip
- 下一篇: Zabbix Database erro