奇数位于偶数前面且顺序不变

来源:互联网 发布:酒店数据接口 编辑:程序博客网 时间:2024/06/02 02:26

输入一个整数数组,使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。


/** * 方法1:放到临时的数组再整合,空间消耗 */class Solution1 {    public void reOrderArray(int [] array) {        ArrayList<Integer> oddList = new ArrayList<Integer>();        ArrayList<Integer> evenList = new ArrayList<Integer>();        //存储        for(int i : array){            if(i%2==1) oddList.add(i);            else evenList.add(i);        }        //重新排序        Iterator it = oddList.iterator();        int i=0;        while(it.hasNext()){            array[i++] = (Integer)it.next();        }        it = evenList.iterator();        while(it.hasNext()){            array[i++] = (Integer)it.next();        }    }}/** * 方法2:每找到一个奇数,该段整体后挪,将奇数放到前面 */class Solution2 {    public void reOrderArray(int [] array) {        int i = 0, j = 0, n = array.length; //i往后找奇数的位置,j是i找到的奇数放的位置        while(i < n && j < n){            //找到下一个奇数            while(i < n && array[i] % 2 == 0 ) i++;            if( i == n ) return ;            //挪动中间的偶数            int oddTemp = array[i], index ;            for(index = i;index > j; index-- ) array[index] = array[index - 1];            array[j] = oddTemp;            j++; i++;        }    }}


0 0
原创粉丝点击