【JZ13】輸入一個整數數組,實現一個函數來調整該數組中數字的順序,使得全部的奇數位於數組的前半部分,全部的偶數位於數組的後半部分,並保證奇數和奇數,偶數和偶數之間的相對位置不變。
知識點:數組
難度:☆java
對原數組進行深拷貝,獲得輔助數組。接着遍歷一次輔助數組,把奇數覆蓋到原數組前半部分,再遍歷一次輔助數組,把偶數覆蓋到原數組的後半部分。web
若是內存緊張,對時間要求不高,則能夠使用 in-place 算法。面試
定義兩個指針i
和j
,其中,i
表示已經將奇數放好的下一個位置,j
表示當前遍歷到的位置。算法
開始時,i
和j
都爲0,j
開始遍歷:
一、當array[j]
爲偶數時,則什麼也不作,繼續下一個;
二、當array[j]
爲奇數時,把array[j]
先保存起來,而後把 [i, j-1] 的元素總體日後挪一位,而後把array[j]
賦值給array[i]
。最後i
和j
都日後走一步。數組
package pers.klb.jzoffer.hard; /** * @program: JzOffer2021 * @description: 調整數組順序使奇數位於偶數前面(輔助數組) * @author: Meumax * @create: 2020-08-11 15:36 **/ public class ReOrder { public void reOrderArray(int[] array) { int[] temp = new int[array.length]; for (int i = 0; i < array.length; i++) { temp[i] = array[i]; } int index = 0; // 整理奇數 for (int i : temp) { if (i % 2 != 0) { array[index++] = i; } } // 整理偶數 for (int j : temp) { if (j % 2 == 0) { array[index++] = j; } } } }
時間複雜度:O(N),遍歷了三次數組,第一次深拷貝,第二次找奇數,第三次找偶數。
空間複雜度:O(N),額外建立容量爲 N 的輔助數組。svg
package pers.klb.jzoffer.hard; /** * @program: JzOffer2021 * @description: 調整數組順序使奇數位於偶數前面(in-place算法) * @author: Meumax * @create: 2020-08-11 15:36 **/ public class ReOrder { public void reOrderArray(int[] array) { int i = 0; // 已經將奇數放好的下一個位置 int j = 0; // 遍歷下標 while (j < array.length) { if (array[j] % 2 != 0) { insert(array,j,i); i++; } j++; } } /** * 把 array 的 from 位置元素放到 to 位置,原來 [to, from-1] 總體日後挪一步 * * @param array * @param from * @param to */ private void insert(int[] array, int from, int to) { int temp = array[from]; for (int i = from - 1; i >= to; i--) { array[i + 1] = array[i]; } array[to] = temp; } }
時間複雜度:O(N2)。
空間複雜度:O(1),沒有額外的空間佔用。函數
第二種方法等因而時間換空間,筆試建議用最快的解決方法,即方法一。面試的時候能夠提到方法二。spa