leetcode - Sort Colors

leetcode - 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.

click to show follow up.

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 pos0 = -1, pos1 = -1, pos2 = -1;
        int i = 0;
        while(i<nums.size()){
            if(nums[i] == 0){
                nums[++pos2] = 2;
                nums[++pos1] = 1;
                nums[++pos0] = 0;
                
            }
            else if(nums[i] == 1){
                nums[++pos2] = 2;
                nums[++pos1] = 1;
            }
            else if(nums[i] == 2){
                nums[++pos2] = 2;
            }
            i++;
        }
    }
};

分析,显然可以使用桶排序的方法,但是题目中要求使用只遍历一遍的算法。

参考:http://www.cnblogs.com/felixfang/p/3680047.html

具体思路如下: 记录0,1,2三种数字的结尾位置。然后对整个数组进行遍历,遇到0时,将0的数目加一,即对0末尾的位置加一,然后并赋值为0,这时,原本为1的地方被改成了0,自然1的结尾位置也要加一,并赋值为1,同理对2也是这样操作。

如果遇到1,则不用考虑0的位置,只调整1和2即可。

如果遇到2,则只考虑2的位置即可。

简图:

000011112222  0……

000001111222  2……

posted @ 2015-10-05 12:04  cnblogshnj  阅读(99)  评论(0编辑  收藏  举报