題目描述
輸入一個整數數組,實現一個函數來調整該數組中數字的順序,使得所有的奇數位於數組的前半部分,所有的偶數位於位於數組的後半部分,並保證奇數和奇數,偶數和偶數之間的相對位置不變。
思路:i指向數組從左到右第一個偶數,j從i+1的位置向後遍歷,直到找到第一個奇數,此時將該奇數利用插入排序插入到i所在的偶數前面。
public class Main {
public void reOrderArray(int [] array) {
int i = 0;
int j = 0;
int temp = 0;
while(i<array.length&&j<array.length) {
while (i<array.length&&isOddOrEven(array[i]) == 1) {i++;}
j = i + 1;
while (j<array.length&&isOddOrEven(array[j]) == 0) {j++;}
if(j<array.length) {
for (int k = j; k > i; k--) {
temp = array[k];
array[k] = array[k - 1];
array[k - 1] = temp;
}
}
}
}
public static int isOddOrEven(int num){
if(num%2==0){
return 0;
}else{
return 1;
}
}
}
思路二:藉助於隊列和新建一個數組B,對原數組遍歷,奇數放B中,偶數放隊列中,最後將隊列中的偶數防B中。
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
int array[] = new int[]{3,4,4,7,5};
for(int key:reOrderArray(array)){
System.out.print(key+" ");
}
}
public static int[] reOrderArray(int []array) {
int newArray[] = new int[array.length];
Queue<Integer> queue = new LinkedList<Integer>();
int j=0;
for(int i=0; i<array.length; i++){
if(isOddOrEven(array[i])==1){
newArray[j]=array[i];
j++;
}else {
queue.offer(array[i]);
}
}
for(;j<newArray.length;j++){
newArray[j] = queue.poll();
}
return newArray;
}
public static int isOddOrEven(int num){
if(num%2==0){
return 0;
}else{
return 1;
}
}
}
變形題:如果不要求奇數和奇數,偶數和偶數之間的相對位置不變。可以採用類似於快排的方法。如下:
public class Solution {
public void reOrderArray(int [] array) {
int i = 0;
int j = array.length-1;
int temp = 0;
while(i<j){
while(isOddOrEven(array[j])==1){j--;}
while(isOddOrEven(array[i])==0){i++;}
if(i<j){
temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
}
public int isOddOrEven(int num){
if(num%2==0){
return 0;
}else{
return 1;
}
}
}