75. Sort Colors

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.

三種顏色,把顏色排序,按照紅、白、藍的順序,其中顏色對應的是0,1,2.


代碼:


參考代碼

解題思路:兩個指針 i0,i2,for循環遍歷,如果遇到的數字是2,那么和末尾i2指向的交換,然后i2向前移動一位,如果交換后仍然是2,那么繼續交換移位;如果nums[i]是0,那么和i0指向的位置交換,然后i0向后移動一位;最后如果i已經和i2重合,說明遍歷結束。


運行結果展示:


測試

Sort Colors

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

推薦閱讀更多精彩內容