剑指offer13:数组[奇数,偶数],奇数偶数相对位置不变。

1. 题目描述

  输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。

2. 思路和方法

  array[i]%2==0用vector的push_back()的函数实现存储。result_odd.insert(result_odd.end(), result_even.begin(), result_even.end())    //在end()前插入[result_even.begin(), result_even.end()]区间的元素。

3. C++核心代码

 1 class Solution {
 2 public:
 3     void reOrderArray(vector<int> &array) {
 4         vector<int> result_even, result_odd;
 5         for(int i=0;i<array.size();i++)
 6         {
 7             if(array[i]%2==0){
 8                 result_even.push_back(array[i]);
 9             }
10             else{
11                 result_odd.push_back(array[i]);
12             }
13         }
14         result_odd.insert(result_odd.end(),result_even.begin(),result_even.end());
15         array = result_odd;
16     }
17 };
View Code

 

posted @ 2019-08-25 13:02  wxwreal  阅读(279)  评论(0编辑  收藏  举报