剑指offer--面试题14

#include "stdafx.h"
#include <iostream>

using namespace std;

//调整数组顺序使奇数位于偶数前
void OddEvenSeparated(int* array, int length)
{
    int indexfront = 0;
    int indexback = length - 1;
    
    bool bFinshed = false;
    while(indexfront < length-1 && !bFinshed)
    {
        if((array[indexfront] & 0x1) != 1)
        {
            while(indexfront < indexback)
            {
                if((array[indexback] & 0x1) == 1)
                {
                    int temp = array[indexback];
                    array[indexback] = array[indexfront];
                    array[indexfront] = temp;
                    indexback--;
                    break;
                }
                indexback--;
            }
            if(indexfront == indexback)
                bFinshed = true;
        }
        indexfront++;

    }
}

int main(int argc, char* argv[])
{
    const int length = 6;
    int array[length] = {1,2,3,4,5,3};
    OddEvenSeparated(array,length);
    for(int i=0; i<length; i++)
    {
        cout<<array[i]<<'	';
    }
    cout<<endl;

    return 0;
}

面试题14:调整数组顺序使奇数位于偶数前

自己所写代码如上所示,初步满足要求,O(n)时间复杂度。

 注意一点:用a & 0x1 代替%2来判断奇偶时,千万写成(a & 0x1) == 1,优先级不同啊!

               所以必须加括号(a & 0x1)

由于时间过于紧迫,而且还有其他比较重要的事情要做,不得已对面试题的理解可能不会那么‘锱铢必较’了。。。

更侧重于想法方面,对代码编写方面也不会基本亲手编写一遍了。。。

速度>质量了。。。

清醒时做事,糊涂时读书,大怒时睡觉,独处时思考; 做一个幸福的人,读书,旅行,努力工作,关心身体和心情,成为最好的自己 -- 共勉
原文地址:https://www.cnblogs.com/hello-yz/p/3251726.html