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重合,說明遍歷結束。
運行結果展示:
測試