1.题目描述
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
2.算法描述
方法1:用两个队列odd,even来存储数组中的奇数和偶数。然后将奇数和偶数存入原数组。
方法2:用插入排序思想或者冒泡排序的思想。
插入排序的工作方式是从第2个数开始从左往右扫描(称为当前数),将当前数和当前数之前的数逐个从右往左比较,如果当前数较小(如果是升序排序),则将当前数之前的数后移。
在这里,我们就从2个数从左往右扫描,如果是奇数,将这个奇数和它之前的数逐个从右往左比较,如果之前的数是偶数,则将之前的数后移。
3.代码描述
3.1.Java代码
//方法1:空间换时间
import java.util.*;
public class Solution {
public void reOrderArray(int [] array) {
Queue<Integer> odd = new LinkedList<>();
Queue<Integer> even = new LinkedList<>();
for(int a: array){
if(a%2==1) odd.offer(a);
else even.offer(a);
}
int i = 0;
while(!odd.isEmpty()) array[i++] = odd.poll();
while(!even.isEmpty()) array[i++] = even.poll();
}
}
//方法2:插入排序思想
public class Solution {
public void reOrderArray(int [] array) {
for(int i=1;i<array.length;i++){
int t = array[i];
if (t%2==1){
int j = i-1;
while(j>=0 && array[j]%2==0){
array[j+1] = array[j];
j--;
}
array[j+1] = t;
}
}
}
}
//方法2:冒泡排序思想
public class Solution {
public void reOrderArray(int [] array) {
for(int i=array.length-1;i>0;i--){
for(int j=0; j<i;j++)
if(array[j]%2==0 && array[j+1]%2==1){
int t = array[j];
array[j] = array[j+1];
array[j+1] = t;
}
}
}
}
3.2.Python代码
//方法1:用空间换时间
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
odd = []
even = []
for a in array:
odd.append(a) if a%2==1 else even.append(a)
i = 0
while odd:
array[i] = odd.pop(0)
i += 1
while even:
array[i] = even.pop(0)
i += 1
return array
//方法2:插入排序思想
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
for i in range(1,len(array)):
t = array[i]
if t%2==1:
j = i-1
while j>=0 and array[j]%2==0:
array[j+1] = array[j]
j -= 1
array[j+1] = t
return array
//方法2:冒泡排序思想
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
for i in range(len(array)-1,0,-1):
for j in range(i):
if array[j]%2==0 and array[j+1]%2==1:
array[j],array[j+1] = array[j+1], array[j]
return array