Given an array with n objects colored red, white or blue, sort them in-place 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.
Note: You are not suppose to use the library's sort function for this problem.
Example:
Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2]
Follow up:
- A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. - Could you come up with a one-pass algorithm using only constant space?
这道题目给了我们一个颜色的array,让我们sort一下,按照0,1,2的顺序。根据题目要求,我们只能遍历array一次,可以用到two pointers来实现。设一个指针red 在开头,blue 在最后。想法就是,遇到红色0,就交换,把0放到最左边去;遇到蓝色2就交换,把2都放到最右边去,这样1就会被保留在最中间。需要注意的是,当把蓝色2交换完毕之后,需要i--, 停留 i 在原地一次,因为还需要继续检查 被2交换回来的数字。那当遇到红色0,交换完毕不需要停留i 的原因是, 交换回来的只可能是1,对于1,我们不需要做任何处理,直接过就可以。
关键词:Array
关键点:用two pointers,一头一尾放置红色和蓝色,保留白色在中间
class Solution { public: void sortColors(vector<int>& nums) { int red = 0; int blue = nums.size() - 1; int temp; for (int i = 0; i <= blue; ++i) { if (nums[i] == 0) { swap(nums[i], nums[red]); red++; } else if (nums[i] == 2) { swap(nums[i], nums[blue]); blue--; i--; } } } void swap(int & a, int & b) { int temp = a; a = b; b = temp; } };