Sort Colors 颜色排序(只有3类值的排序)

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.

---------------------------------------------------------------------------------------------------------------------------------------------------------


这个问题实质上就是对于0, 1, 2的序列进行排序。由于只有3类值。

我们可以实现一个时间复杂度为 O ( n ) , 空间复杂度为 O ( 1 )的算法。

核心的思想是:

将0 的全都放到left边, 将2 的全都放到right边,

最后,就是排好序的了。

为了实现这个思想,

我们需要有一个left 指针,和一个right指针。

让left指针前面的都是0, right指针后面的都是1。

同时一个cur指针,从左到右遍历这个数组。

1. cur 遍历到0的时候,我们将0 与 left 指向的值互换。left++;

2. 当cur遍历到2的时候,我们将2 与right指向的值互换,right--;

3. 当cur遍历到1的时候,cur++, 不用管,继续往下走。

4. 注意:如果0已经放在符合要求的位置了,left++, cur++

               如果2已经放在符合要求的位置了,说明后面的都是2了,可以结束了。


运行时间:



代码:

    public void sortColors(int[] nums) {
        if (nums == null || nums.length == 0 || nums.length == 1) {
            return;
        }
        int left = 0;
        int right = nums.length - 1;
        int cur = left;
        while (cur <= right) {
            if (nums[cur] == 0) {
                if (cur == left) {// already on the right place
                    cur++;
                    left++;
                } else {
                    nums[cur] = nums[left];// swap
                    nums[left] = 0;
                    left++;
                }
            } else if (nums[cur] == 1) {
                cur++;
            } else if (nums[cur] == 2) {
                if (cur == right) {// already on the right place, can return 
                    return;
                }
                nums[cur] = nums[right];
                nums[right] = 2;// swap
                right--;
            }
        }
    }


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值