知识点:数组
一、题目描述:
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
二、解题思路:
创建一个新的数组,遍历两次原数组,将原数组中的奇数先push进去,再将偶数push进去,最后用新数组数据覆盖原数组
三、代码实现:
C++:
class Solution {
public:
void reOrderArray(vector<int> &array) {
//创建新数组
vector<int> nums;
//遍历array数组,将奇数存入nums中
for(int i=0; i<array.size(); i++){
if(array[i]%2 == 1){
nums.push_back(array[i]);
}
}
//遍历array数组,将偶数存入nums中
for(int i=0; i<array.size(); i++){
if(array[i]%2 == 0){
nums.push_back(array[i]);
}
}
//用nums数组覆盖array数组
array = nums;
}
};
python:
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
nums = []
for ele in array:
if ele%2 == 1:
nums.append(ele)
for ele in array:
if ele%2 == 0:
nums.append(ele)
array = nums
return array#需要返回
2、与可以借用两个辅助数组,遍历一次原数组,遇到奇数添加到第一个辅助数组中,遇到偶数添加到第二个辅助数组中,最后对两个数组进行拼接
python:
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
odd,even = [],[]
for ele in array:
odd.append(ele) if ele%2 == 1 else even.append(ele)
return odd + even