java数据结构和算法(11)调整顺序使奇数位于偶数前

2019-06-06  本文已影响0人  ngu2008
public class Solution {
    public void reOrderArray(int [] array) {
        
    }
}
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;
    }
}
上一篇下一篇

猜你喜欢

热点阅读