输入一个长度为 n 整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前面部分,所有的偶数位于数组的后面部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型vector
* @return int整型vector
*/
//2 4 6 5 7
vector<int> reOrderArray(vector<int>& array) {
// write code here
// vector<int> temp;
// temp.reserve(array.size());
// for(int idx = 0; idx < array.size(); ++idx){
// if(array[idx] % 2 == 1){
// temp.push_back(array[idx]);
// }
// }
// for(int idx = 0; idx < array.size(); ++idx){
// if(array[idx] % 2 == 0){
// temp.push_back(array[idx]);
// }
// }
// array.swap(temp);
// return array;
//暴力法↑
//冒泡思想:每次将偶数都冒泡到最右边
/* case:
1 5 7 8 9 10 2 1
1 5 7 9 8 10 1 2
1 5 7 9 8 1 10 2
1 5 7 9 1 8 10 2
*/
int n = array.size();
for(int i = n - 1; i > 0; --i){
for(int j = 0; j < i; ++j){
if(array[j] % 2 == 0 && array[j+1] % 2 != 0){
swap(array[j], array[j + 1]);
}
}
// for(auto &elem: array){
// cout << elem << " ";
// }
// cout << endl;
}
return array;
}
};