[Leet Code] 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中已经给出了,但是需要遍历两遍,其他的类似方法也需要遍历一遍以上,例如交换元素的方法,第一遍把所有0换到前面,第二遍把所有1接着换到第一遍最后的位置,2自动换到了最后面。那么看看有没有只需要遍历一遍的方法。偶尔看到有这样一种解法,觉得挺巧妙的,但是没有给出太多解释,仔细分析了几遍代码,详细的介绍下:

核心思路就是用三个游标记录最后一个0,1,2的索引,当插入0时,所有索引一次往后移动一个位置(1,2往后复制一个位置),类似的,当插入1时,2往后复制一个位置,插入2时,直接更新2的索引,并进行插入操作。

代码如下:

<span style="font-size:14px;">void sortColors(vector<int>& nums) {
        int iLastZero = -1//three indexes...
        int iLastOne = -1;
        int iLastTwo = -1;
        for(size_t i = 0; i < nums.size(); ++i)
        {
            if (0 == nums[i])//insert 0
            {
                nums[++iLastTwo] = 2;//index of two backwards a 2
                nums[++iLastOne] = 1;
                nums[++iLastZero] = 0;
            }
            else if (1 == nums[i])
            {
                nums[++iLastTwo] = 2;
                nums[++iLastOne] = 1;
            }
            else if (2 == nums[i])
            {
                nums[++iLastTwo] = 2;
            }
            else
            {
                //for other cases.
            }
        }
    }</span></span>

看一个具体的例子:
给定一个数组:nums: [1,2,0,1,0],以下是每一次遍历后的处理结果。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值