igt 三色排序問題

來源:互聯網
上載者:User

給定一個字串裡面只有"R" "G" "B" 三個字元,請排序,最終結果的順序是R在前 G中 B在後。
要求:空間複雜度是O(1),且只能遍曆一次字串。
http://write.blog.csdn.net/postedit 在july大牛的部落格中第八節有這個問題的答案。

做題的時候感覺如果要是兩個字元排序,就是快排中的一趟,兩個指標就搞定了,但是三個字元也想到可能要用三個指標,但是不知道具體怎麼移動,看了july的部落格恍然大悟,感覺好簡單呀,具體思路如下:

一前begin,一中current,一後end,倆倆交換。

1、current遍曆,整個數組序列,current指1不動,
2、current指r,與begin交換,而後current++,begin++,
3、current指b,與end交換,而後,current不動,end--。

三個指標分別控制rgb三種顏色的位置,開始begin current指向第一個,end指向最後一個

while( current<=end )     
{          
  if( array[current] ==‘r’ )          
   {              
      swap(array[current],array[begin]);               
      current++;               
      begin++;         
   }          
   else if( array[current] == ‘g’ )         
   {              
      current++;         
   }
         
   else //When array[current] =‘b’
   {            
      swap(array[current],array[end]);             
      end--;         
   }   
}

之前還看到拓展情況,比如四色,四個字元的該如何處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.