前提條件
- 時間複雜度:O(n)
- 空間複雜度:O(1)
思路
- 若陣列長度為偶數,那麼其中奇數元素和偶數元素的個數相等;若陣列長度為奇數,那麼其中奇數元素和偶數元素的個數相差 1;我們先校驗奇數元素個數和偶數元素個數是否合法,若不合法,則直接丟擲異常;
- 根據陣列中奇數元素的個數和偶數元素的個數的大小來判斷結果陣列中第一個元素應該是奇數還是偶數;
- 感覺程式碼寫的很醜,暫時想不到更加優雅的寫法了。。。
import java.util.Arrays;
class Solution {
public static void main(String[] args) {
System.out.println(Arrays.toString(oddEvenHandle(new int[]{2, 2, 3})));
System.out.println(Arrays.toString(oddEvenHandle(new int[]{1, 2, 3, 4})));
System.out.println(Arrays.toString(oddEvenHandle(new int[]{1, 2, 3, 4, 4})));
System.out.println(Arrays.toString(oddEvenHandle(new int[]{1, 2, 3, 4, 5})));
System.out.println(Arrays.toString(oddEvenHandle(new int[]{1, 2, 3, 4, 5, 6})));
System.out.println(Arrays.toString(oddEvenHandle(new int[]{1, 2, 3, 4, 5, 6, 7})));
System.out.println(Arrays.toString(oddEvenHandle(new int[]{1, 2, 3, 4, 5, 6, 7, 8})));
System.out.println(Arrays.toString(oddEvenHandle(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 8})));
System.out.println(Arrays.toString(oddEvenHandle(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 8, 8})));
}
private static int[] oddEvenHandle(int[] array) {
if (array == null || array.length == 0) {
return array;
}
int oddCount = 0, evenCount = 0;
for (int ele : array) {
if (ele % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}
if (Math.abs(oddCount - evenCount) > 1) {
throw new IllegalArgumentException(String.format("oddCount = %d, evenCount = %d", oddCount, evenCount));
}
boolean oddHead = false;
if (oddCount >= evenCount) {
oddHead = true;
}
int oddPoint = 0, evenPoint = 0;
for (int i = 0; i < array.length; i++) {
if (oddHead) {
if (i % 2 == 0) {
// 奇數
if (array[i] % 2 == 0) {
if (oddPoint < i) {
oddPoint = i;
}
while (array[oddPoint] % 2 == 0) {
oddPoint++;
}
swap(array, i, oddPoint);
}
} else {
// 偶數
if (array[i] % 2 == 1) {
if (evenPoint < i) {
evenPoint = i;
}
while (array[evenPoint] % 2 == 1) {
evenPoint++;
}
swap(array, i, evenPoint);
}
}
} else {
if (i % 2 == 0) {
// 偶數
if (array[i] % 2 == 1) {
if (evenPoint < i) {
evenPoint = i;
}
while (array[evenPoint] % 2 == 1) {
evenPoint++;
}
swap(array, i, evenPoint);
}
} else {
// 奇數
if (array[i] % 2 == 0) {
if (oddPoint < i) {
oddPoint = i;
}
while (array[oddPoint] % 2 == 0) {
oddPoint++;
}
swap(array, i, oddPoint);
}
}
}
}
return array;
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}