- 輸入一個(gè)整數(shù)數(shù)組,實(shí)現(xiàn)一個(gè)函數(shù)來調(diào)整該數(shù)組中數(shù)字的順序怔锌,使得所有的奇數(shù)位于數(shù)組的前半部分,所有的偶數(shù)位于數(shù)組的后半部分变过,并保證奇數(shù)和奇數(shù)埃元,偶數(shù)和偶數(shù)之間的相對(duì)位置不變。媚狰。完成如下代碼:
public class Solution {
public void reOrderArray(int [] array) {
}
}
- 思路:遍歷數(shù)組岛杀,將奇數(shù)和偶數(shù)分別存入兩個(gè)集合,再寫入數(shù)組哈雏。
- 代碼
public class Solution {
public void reOrderArray(int [] array) {
if (array == null || array.length <= 1) {
return;
}
ArrayList<Integer> odds = new ArrayList<>();
ArrayList<Integer> evens = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 1) {
odds.add(array[i]);
} else {
evens.add(array[i]);
}
}
for (int i = 0; i < odds.size(); i++) {
array[i] = odds.get(i);
}
int len = odds.size();
for (int i = 0; i < evens.size(); i++) {
array[len + i] = evens.get(i);
}
odds.clear();
odds=null;
evens.clear();
evens=null;
}
}