题目描述
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
分析
使用两个队列,一个存奇数,一个存偶数,然后依次将数赋值回原数组
import java.util.*;
public class Solution {
public void reOrderArray(int [] array) {
if(array == null || array.length == 1) {
return;
}
Queue<Integer> oddQueue = new LinkedList<>();
Queue<Integer> evenQueue = new LinkedList<>();
for(int i = 0; i < array.length; i++) {
if(isOddNum(array[i])) {
oddQueue.offer(array[i]);
}else {
evenQueue.offer(array[i]);
}
}
int i = 0;
while(!oddQueue.isEmpty()) {
array[i++] = oddQueue.poll();
}
while(!evenQueue.isEmpty()) {
array[i++] = evenQueue.poll();
}
}
private static boolean isOddNum(int num) {
if((num & 1) == 1){
return true;
}
return false;
}
}