zoukankan      html  css  js  c++  java
  • 剑指offer-面试题21-调整数组顺序使奇数位于偶数前面-双指针

    /*
    题目:
    	调整数组顺序使奇数位于偶数前面。
    */
    /*
    思路:
    	双指针:
    		一个指针last用于遍历,当为奇数时+1,
    		当为偶数时,交换last和pre指向的值,向前移动pre指针。
    */
    #include<iostream>
    #include<string.h>
    #include<algorithm>
    #include<cmath>
    #include<stdio.h>
    using namespace std;
    
    void reOrderArray(vector<int> &arr) {
        if(arr.empty()) return;
        int pre = 0,last = 0;
        int length = arr.size();
    
        while(last < length){
            if(arr[last] & 0x1 == 1){
                if(last != pre){
                    int temp = arr[last];
                    arr[last] = arr[pre];
                    arr[pre] = temp;
                }
                pre++;
            }
            last++;
        }
    }
    
    
    int main(){
        int a[] = {2,4,6,8,1,3,5};
        vector<int> arr(a,a+7);
        reOrderArray(arr);
        for(int i = 0; i < 7; i++){
            cout<<arr[i]<<" ";
        }
    
    }
    

       

  • 相关阅读:
    双指针
    二分查找
    二叉树
    递归思想
    排序算法
    Java常用集合使用方法总结
    攻防世界-PHP文件包含
    正则表达式随笔
    ts 函数
    ts 联合类型
  • 原文地址:https://www.cnblogs.com/buaaZhhx/p/11900938.html
Copyright © 2011-2022 走看看