題目描述
輸入一個整數數組,實現一個函數來調整該數組中數字的順序,使得所有的奇數位於數組的前半部分,所有的偶數位於位於數組的後半部分。
思路
雙指針,但是不穩定
import java.util.Arrays;
class Test {
public void reOrderArray(int [] array) {
int n = array.length;
if (n <= 0) return;
int i = 0;
int j = n - 1;
while (i < j) {
// i指向奇數,繼續向後走,直到找到偶數
while (i < j && (array[i] & 1) != 0)
i++;
// j指向偶數,繼續向前走,直到找到奇數
while (i < j && (array[j] & 1) == 0)
j--;
if (i < j)
swap(array, i, j);
}
}
public void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
空間換時間,可以保證穩定
public class Solution {
public void reOrderArray(int [] array) {
int n = array.length;
int[] res = new int[n];
if (n <= 0) return;
int odd_len = 0;
for (int num : array) {
if ((num & 1) == 1)
odd_len++;
}
int j = 0;
for (int i = 0; i < n; i++) {
if ((array[i] & 1) == 1)
res[j++] = array[i];
else if ((array[i] & 1) == 0)
res[odd_len++] = array[i];
}
int i = 0;
for (int num : res)
array[i++] = num;
}
}