题目描述
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
方法一
暴力法,遍历两遍,将奇数偶数分别放到两个数组中,再合并为同一个数组。
public class Solution {
public void reOrderArray(int [] array) {
int m = 0; //奇数个数
int n = 0; //偶数个数
int e = 0;
int length = array.length; //原数组长度
int[] a = new int[length]; //奇数数组
int[] b = new int[length]; //偶数数组
int[] result = new int[length]; //结果数组
for(int i = 0; i<length; i++){
if(array[i]%2==1){
a[m] = array[i];
m++;
}
if(array[i]%2==0){
b[n] = array[i];
n++;
}
}
for(int c = 0;c<m;c++)
{
result[e]=a[c];
e++;
}
for(int d=0;d<n;d++)
{
result[e]= b[d];
e++;
}
for(int f = 0;f<result.length;f++){
array[f] = result[f];
}
}
}
时间复杂度:O(n)
空间复杂度:O(n)
仿快速排序
设置两个指针,i,j
初始: i=0;
- i 遇到偶数时,停。
- j =i+1 ,继续往后,直到遇到奇数
此时,数组下标[i , j-1] 为偶数
- temp = array[i] , 即[i , j-1] 范围内第一个偶数。
令,array[i] = a[j] , [i+1,j-1] 移动到 [i+2,j],temp值填在array[i+1]处
或temp = array[j],即偶数后第一个奇数
[i,j-1] 移动到 [i+1,j],temp = array[i]
public class Solution {
public void reOrderArray(int [] array) {
int i = 0, j = 0;
int temp = 0;
for(i = 0;i<array.length;i++){
for(j=i+1;j<array.length;j++){
if(array[i]%2==0 && array[j]%2==1){
temp = array[j];
//将偶数后移
for(int m = j; m>=i+1;m--){
array[m] = array[m-1];
}
array[i] = temp;
}
}
}
}
}
仿冒泡排序
当前奇数,下一个为偶数的时候交换
public class Solution {
public void reOrderArray(int [] array) {
int temp = 0;
int count = 1;
for(int i = 0;i<array.length && (count!=0);i++){
count = 0;
for(int j=0;j<array.length-1-i;j++){
if(array[j]%2==0 && array[j+1]%2==1){
count++;
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
}