题目描述
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
思路1:
创建一个新数组temp,大小和原数组array一样。遍历原数组array,元素是奇数则放在temp数组的前面,偶数放在后面。
空间复杂度为O(n),时间复杂度为O(n)。
public class Solution {
public void reOrderArray(int [] array) {
//count统计奇数的个数
int count = 0;
//创建和array大小一样的数组temp
int [] temp = new int[array.length];
for(int i = 0; i < array.length; i++)
{
if(array[i] % 2 == 1)
{
//将奇数元素放在前面
temp[count] = array[i];
//统计数count+1,元素后移一位;
//不满足条件时,并且刚好count的索引值为偶数开始索引值
count += 1;
}
}
//将偶数的元素放在count后面
for(int i = 0; i < array.length; i++)
{
if(array[i] % 2 == 0)
{
temp[count] = array[i];
count += 1;
}
}
//将整个temp数组赋值给array数组
for(int i = 0;i<array.length; i++)
{
array[i]=temp[i];
}
}
}
思路二:用插入排序的思想,奇数插入,偶数不动。
public class Solution {
public void reOrderArray(int [] array) {
for(int i = 1;i<array.length;i++)
{
if(array[i] % 2 == 1)//对奇数进行插入
{
int j = i;
int temp = array[i];
//如:奇奇奇偶偶偶 奇
while(j>0 && (array[j-1] % 2 == 0))
{
array[j] = array[j-1];
j--;
}
array[j] = temp;
}
}
}
}