zoukankan      html  css  js  c++  java
  • 剑指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)

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

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

    速度>质量了。。。

    清醒时做事,糊涂时读书,大怒时睡觉,独处时思考; 做一个幸福的人,读书,旅行,努力工作,关心身体和心情,成为最好的自己 -- 共勉
  • 相关阅读:
    洛谷 1339 最短路
    洛谷 1330 封锁阳光大学 图论 二分图染色
    洛谷 1262 间谍网络 Tarjan 图论
    洛谷 1373 dp 小a和uim之大逃离 良心题解
    洛谷 1972 莫队
    洛谷 2158 数论 打表 欧拉函数
    洛谷 1414 数论 分解因数 水题
    蒟蒻的省选复习(不如说是noip普及组复习)————连载中
    关于筛法
    关于整数划分的几类问题
  • 原文地址:https://www.cnblogs.com/hello-yz/p/3251726.html
Copyright © 2011-2022 走看看