劍指offer 13:調整數組順序使奇數位於偶數前面

題目描述

輸入一個整數數組,實現一個函數來調整該數組中數字的順序,使得所有的奇數位於數組的前半部分,所有的偶數位於數組的後半部分,並保證奇數和奇數,偶數和偶數之間的相對位置不變。

法一:

public class Solution {
    public void reOrderArray(int [] array) {
        int oddCnt=0;
        for(int val : array){
            if((val & 0x1) == 1)
                oddCnt++;
        }
        int[] copy = array.clone();
        int i = 0, j = oddCnt;
        for(int val : copy){
            if((val & 0x1) == 1)
                array[i++] = val;
            else
                array[j++] = val;
        }
    }
}

法二:

public class Solution {
    public void reOrderArray(int [] array) {
        for(int i = 0; i < array.length; i++){
            for(int j = 0; j < array.length - 1 - i; j++){
                if(array[j] % 2 == 0 && array[j+1] % 2 != 0){
                    int temp = array[j+1];
                    array[j+1] = array[j];
                    array[j] = temp;
                }
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章