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重合,说明遍历结束。