Sort Colors

来源:互联网 发布:python 画图 编辑:程序博客网 时间:2024/05/21 09:17

题目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.

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?
思路分析:
(1)注意中写的方法:遍历3次,分别统计处0、1、2的个数,根据对应的个数,填充数组中的值;
(2)两个指针:一个慢指针,一个快指针,遍历两次,以0为例子说明,慢指针指向第一个非0的位置,快指针继续移动直至第一个是0的元素,交换快慢指针,继续向后移动,一次遍历将0都排在最左边,1是相同的处理,剩下的2全在最右边;

/*(3)类似于排序,就要从排序的方法着手分析,题目还是挺有意思的,类似于快速排序,3个指针,1个遍历指针mov,一个指针start指向0的第一个,一个指针end指向2的第一个。*/

惭愧,当时竟没有写清楚,又看了一次才能写清楚。
(3)3个指针:指针mov遍历指针,指针start从下标0开始一直指向0,指针end指向最后一个;
1、mov指向1的时候,++mov;
2、mov指向0的时候,与start交换,而后mov++,start++;
3、mov指向2的时候,与end交换,而后mov不动,end–。
为什么,第三步,mov指向2的时候,与end交换之后,mov不动。
因为最终的目的是为了让0、1、2成为有序排列,试想,如果第三步,mov与end交换之前,万一end指向的是0,而mov交换之后,mov此刻指向的是0了,此时,mov能动么?不能动啊,指向的是0,还得与start交换。这样写就很清楚了,汗。

class Solution {public:    void sortColors(vector<int>& nums) {        int size = nums.size();        int start, end, mov;        start = 0;        end = size - 1;        mov = 0;        while (mov <= end) {            if (nums[mov] == 0) {                swap(nums[mov ++], nums[start ++]);            } else if (nums[mov] == 2) {                swap(nums[mov], nums[end --]);            } else {                ++ mov;            }        }        return;    }};

参考:
[1] http://blog.csdn.net/zxzxy1988/article/details/8596144
[2] http://blog.chinaunix.net/uid-29246150-id-4088302.html
[3] http://blog.csdn.net/hackbuteer1/article/details/8035261 讲得很清楚。

0 0
原创粉丝点击