题目描述

输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。

分析

使用两个队列,一个存奇数,一个存偶数,然后依次将数赋值回原数组

  1. import java.util.*;
  2. public class Solution {
  3. public void reOrderArray(int [] array) {
  4. if(array == null || array.length == 1) {
  5. return;
  6. }
  7. Queue<Integer> oddQueue = new LinkedList<>();
  8. Queue<Integer> evenQueue = new LinkedList<>();
  9. for(int i = 0; i < array.length; i++) {
  10. if(isOddNum(array[i])) {
  11. oddQueue.offer(array[i]);
  12. }else {
  13. evenQueue.offer(array[i]);
  14. }
  15. }
  16. int i = 0;
  17. while(!oddQueue.isEmpty()) {
  18. array[i++] = oddQueue.poll();
  19. }
  20. while(!evenQueue.isEmpty()) {
  21. array[i++] = evenQueue.poll();
  22. }
  23. }
  24. private static boolean isOddNum(int num) {
  25. if((num & 1) == 1){
  26. return true;
  27. }
  28. return false;
  29. }
  30. }