调整01的位置,使得0在基数位1在偶数位,并且只能一次扫描,没有额外空间

504 篇文章 0 订阅

转自出处

Modified 2 color sort problem i.e. you are given an array of integers 
containing only 0s and 1s.You have to place all the 0s in even position and 
1s in odd position. And if suppose, no. of 0s exceed no. of 1s or vice versa 
then keep them untouched. Do that in ONE PASS and without taking extra 
memory (modify the array in-place). 
For e.g. 
Input Array: {0,1,1,0,1,0,1,0,1,1,1,0,0,1,0,1,1} 
Output Array: {0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1} 

分析:

1、题目一很容易联想到partition的作法,不过考虑到题目要求“if suppose no. of 0s exceed no. of 1s or vice versa then keep them untouched”,所以临界情况要特别注意,否则得到的结果很可能是类似于{0 1 0 1 0 1 0 1 0 1 1 1 0 1 0 1 1 }这样的结果,显然这不是题目所要求的输出。


void RearrangeO1(int seq[],int n)
{
    int index0 = 0;
    int index1 = 1;
    ///类似于partition操作
    while(true)
    {
        while(index0 < n && seq[index0] == 0 )
            index0 += 2;
        if(index0 >= n)
            break;
        while(index1 < n && seq[index1] == 1 )
            index1 += 2;
        if(index1 >= n)
            break;
        //交换
        int temp = seq[index0];
        seq[index0] = seq[index1];
        seq[index1] = temp;
    }
    /临界情况处理
    奇数位置上已经全部为0,处理偶数位置:1尽量往前排
    if(index0 >= n)
    {
        int indexend = (n % 2 == 0) ? n - 1 : n - 2;
        while(true)
        {
            while(index1 < n && seq[index1] == 1)
                index1 += 2;
            while(indexend > index1 && seq[indexend] == 0)
                indexend -= 2;
            if(index1 >= indexend)
                break;
            /交换
            int temp = seq[index1];
            seq[index1] = seq[indexend];
            seq[indexend] = temp;
        }
    }
    偶数位置上已经全部为1,处理奇数位置:0尽量往前排
    else
    {
        int indexend = (n % 2 == 0) ? n - 2 : n - 1;
        while(true)
        {
            while(index0 < n && seq[index0] == 0)
                index0 += 2;
            while(indexend > index0 && seq[indexend] == 1)
                indexend -= 2;
            if(index0 >= indexend)
                break;
            /交换
            int temp = seq[index0];
            seq[index0] = seq[indexend];
            seq[indexend] = temp;
        }
    }
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值