Sort Colors —LeetCode

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.

1、顺序遍历,记录 red, white, and blue的count

void sortColors(int A[], int n) {
        if(n==1) return;
        int redCount=0;
        int whiteCount=0;
        for(int i=0;i<n;i++)
        {
            if(A[i]==0) redCount++;
            if(A[i]==1) whiteCount++;
        }
        for(int i=0;i<redCount;i++)
            A[i]=0;
        for(int i=0;i<whiteCount;i++)
            A[i+redCount]=1;
        for(int i=redCount+whiteCount;i<n;i++)
            A[i]=2;
    }
2、同方法1,使用一个数组记录cout

void sortColors(int A[], int n) {
        if(n<=1) return;
        int count[3]={0};
        for(int i=0;i<n;i++)
        {
            count[A[i]]++;
        }
        int index=0;
        for(int i=0;i<3;i++)
        {
            while(count[i])
            {
             A[index]=i;
             count[i]--;
             index++;
            }
        }
    }

3、两个指针,一次遍历

//由于在第一个while循环中,我们使用的是index与twoIndex作为进行下一次循环判断的依据,

首先我们可以判断,index走过之后,index之前的之一定为0或1(值为2时一定会与twoIndex进行swap)

我们应注意:

若先判断A[index]==0&&index>zeroIndex后判断A[index]==2&&index<twoIndex时,当index与twoIndex(此时twoIndex指向一个0)进行了一次swap,由于index下一步的动作是++,我们可以保证index走过的位置一定为0或1,但可能并未排好序。

故我们应该保证,在一次while循环index++前,index指向的位置必须不再进行swap,即已经排好序,我们不能保证与twoIndex进行swap交换的值是0还是1,故应该在与twoIndex交换后再与zeroIndex比较以确保排序。

void sortColors(int A[], int n) {
        if(n<=1) return;
       int zeroIndex=0;
       int twoIndex=n-1;
       int index=0;
       while(index<=twoIndex)
       {
           while(A[index]==2&&index<twoIndex)
           {
               swap(A[index],A[twoIndex]);
               twoIndex--;
           }
           while(A[index]==0&&index>zeroIndex)
           {
               swap(A[zeroIndex],A[index]);
               zeroIndex++;
           }
           index++;
       }
    }

4、两个指针,较容易理解的版本

//对index指向的位置多次判断,直至A[index]=1,index++

void sortColors(int A[], int n) {
        if(n<=1) return;
       int zeroIndex=0;
       int twoIndex=n-1;
       int index=0;
       while(index<=twoIndex)
       {
           if(A[index]==0&&index>zeroIndex)
           {
               swap(A[zeroIndex],A[index]);
               zeroIndex++;
           }
           else
           {
               if(A[index]==2&&index<twoIndex)
               {
                   swap(A[index],A[twoIndex]);
                   twoIndex--;
               }
               else 
                   index++;
           }
       }
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值