剑指offer--面试题14

时间:2023-03-09 17:43:43
剑指offer--面试题14
#include "stdafx.h"
#include <iostream> using namespace std; //调整数组顺序使奇数位于偶数前
void OddEvenSeparated(int* array, int length)
{
int indexfront = ;
int indexback = length - ; bool bFinshed = false;
while(indexfront < length- && !bFinshed)
{
if((array[indexfront] & 0x1) != )
{
while(indexfront < indexback)
{
if((array[indexback] & 0x1) == )
{
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 = ;
int array[length] = {,,,,,};
OddEvenSeparated(array,length);
for(int i=; i<length; i++)
{
cout<<array[i]<<'\t';
}
cout<<endl; return ;
}

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

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

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

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

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

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

速度>质量了。。。