1. 程式人生 > >按奇偶排序陣列

按奇偶排序陣列

給定一個非負整數陣列 A,返回一個由 A 的所有偶數元素組成的陣列,後面跟 A 的所有奇數元素。

你可以返回滿足此條件的任何陣列作為答案。

示例:

輸入:[3,1,2,4]
輸出:[2,4,3,1]
輸出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也會被接受。

提示:

  1. 1 <= A.length <= 5000
  2. 0 <= A[i] <= 5000

題目分析:

一、使用額外空間

新定義一個數組,然後在給定的陣列中遍歷奇偶數,將最後的資料存入新陣列中

程式碼實現:

public int
[] sortArrayByParity(int[] A) { int[] temp = new int[A.length]; int begin = 0; int end = A.length - 1; for (int i = 0; i < A.length; i++) { if (A[i] % 2 == 0){ temp[begin] = A[i]; begin++; } else{ temp[end] = A[i]; end--
; } } return temp; }

二、不使用額外空間

設定雙指標,從陣列的首位和末尾遍歷,符合條件(偶數要排在前面,奇數要排在後面)就交換

程式碼實現:

public int[] sortArrayByParity(int[] A) {
   int i = 0;
   int j = A.length - 1;

   while (i < j){
       if (A[i] % 2 == 1 && A[j] % 2 == 0) {
           int temp = A[j];
           A[
j] = A[i]; A[i] = temp; } if (A[i] % 2 == 0){ i++; } if (A[j] % 2 == 1){ j--; } } return A; }

主函式:

public static void main(String[] args) {
   A1 a = new A1();
   int[] test = {3,1,2,4,1};
   int[] res = a.sortArrayByParity(test);
   for (int i = 0; i < res.length; i++) {
       System.out.print(res[i] + " ");
   }
}

執行結果:

4 2 1 3 1