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]<<" ";
        }
    
    }
    

       

  • 相关阅读:
    U132973 双生独白
    Remmarguts' Date(A* 短路)
    P3908 数列之异或
    P1469 找筷子
    P1759 通天之潜水
    P2356 弹珠游戏
    P7072 直播获奖
    P7074 方格取数
    CSP2020二轮游记
    P6205 [USACO06JAN]Dollar Dayz S
  • 原文地址:https://www.cnblogs.com/buaaZhhx/p/11900938.html
Copyright © 2011-2022 走看看