【Sort Colors】cpp
题目:
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.
Note:
You are not suppose to use the library's sort function for this problem.
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 an one-pass algorithm using only constant space?
代码:
class Solution { public: void sortColors(vector<int>& nums) { int p0 = 0; int p2 = nums.size()-1; int i = 0; while ( i<=p2 ) { if ( nums[i]==0 ) { std::swap(nums[i++], nums[p0++]); continue; } if ( nums[i]==2 ) { std::swap(nums[i],nums[p2--]); continue; } i++; } } };
tips:
双指针技巧。
需要注意的是指针i什么时候移动。
1) 如果发现nums[i]==0,则swap之后i后移,p0后移。
2) 如果发现nums[i]==2,则swap之后i不动,p2前移。
3) 终止条件是i>p2
要保证指针i始终处于p0和p2之间:
因为1)的交换后,肯定保证nums[i]==1。
但是2)的交换后,不一定保证nums[i]是什么,因此i暂时不动。
但是,既然1)交换后肯定保证nums[i]==1,可不可以不直接nums[i++],而是把移动i的任务交给最后的i++呢?
这样做的不太方便的,因为如果首个元素就是0,就会导致i<p0了,所以最好这样写。
=============================================
第二次过这道题,核心在于记住“因为1)的交换后,肯定保证nums[i]==1。”
class Solution { public: void sortColors(vector<int>& nums) { int zero = 0; int two = nums.size()-1; int i = 0; while ( i<=two ) { if ( nums[i]==0 ) { swap(nums[i++], nums[zero++]); } else if ( nums[i]==2 ) { swap(nums[i], nums[two--]); } else { i++; } } } };