leetcode 刷题之路 90 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.

去掉题目背景,其实就是给出一个含有数字0,1,2的数组,对其进行排序。

O(n)复杂度算法思路:使用下标i,j分别指向数组的起始位置和结束位置,使用下标k来遍历数组,当k处数字为0时和位置i处数字交换,同时i和k递增,当k处数字为2时,和位置j处数字交换,同时j递减,循环执行以上步骤直到k大于j。

需要特别强调的是,位置k处数字和位置j处数字交换后,j递减,k不递增,这是因为原来j处的数据可能为2,如果把2交换到k位置后k递增,那么这个2处在错误的位置且没有处理的机会了。

但是位置k处和数字和位置i处数字交换后,i和k可以同时递增是因为交换后的位置位于i后面,i还会到达此位置进行处理。

Accepted Solution:

class Solution {
public:
    void sortColors(int A[], int n) 
    {
        int i=0,j=n-1,k=0;
        while(k<=j)
        {
            if(A[k]==0)
                swap(A[k++],A[i++]);
            else if(A[k]==2)
                swap(A[k],A[j--]);
            else
                k++;
        }
    }
    void swap(int &a,int &b)
    {
        int temp=a;
        a=b;
        b=temp;
    }
};



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值