zoukankan      html  css  js  c++  java
  • 调整数组顺序使奇数位于偶数前面 【微软面试100题 第五十四题】

    题目要求:

      输入一个整数数组,调整数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。

      要求时间复杂度为O(n).

      参考资料:剑指offer第14题。

    题目分析:

      使用两个指针,pBegin和pEnd,pBegin从开头往后遍历,pEnd从结尾往前遍历,当pBegin遇到偶数和pEnd遇到奇数时,交换两个数,然后继续遍历,直到pBegin>pEnd,则结束。

    代码实现:

    #include <iostream>
    
    using namespace std;
    
    void ReorderOddEven(char *pIn,int len);
    
    int main(void)
    {
        char pStr[] = "4372173283475738495734858394";
    
        cout << "原数组为(乱序)              :" << pStr << endl;
        ReorderOddEven(pStr,strlen(pStr));
        cout << "调整后为(前位奇数,后为偶数):" << pStr << endl;
        return 0;
    }
    void ReorderOddEven(char *pIn,int len)
    {
        if(pIn==NULL || len<=0)
            return ;
        char *pBegin = pIn;
        char *pEnd = pIn+len-1;
        while(pBegin<pEnd)
        {
            //向后移动pBegin,直到值为偶数
            while(pBegin<pEnd && (*pBegin&0x01)!=0)
                pBegin++;
            //向前移动pEnd,直到值为奇数
            while(pBegin<pEnd && (*pEnd&0x01)==0)
                --pEnd;
            if(pBegin<pEnd)
            {
                char temp = *pBegin;
                *pBegin = *pEnd;
                *pEnd = temp;
            }
        }
    }
  • 相关阅读:
    poj2346
    poj3748
    poj1205
    PostThreadMessage 使用注意问题
    CBitmap Detach DeleteObject关系
    音视频编码技术与格式大全
    利用 DirectShow 开发自己的 Filter
    VC+DirectShow对视频进行图片处理VC教程电脑教程之家.htm
    Directx报错01
    深圳超多维光电子有限公司
  • 原文地址:https://www.cnblogs.com/tractorman/p/4090241.html
Copyright © 2011-2022 走看看