剑指offer_14(调整数组顺序使得奇数位于偶数前面)

来源:互联网 发布:雅马哈摩托 知乎 编辑:程序博客网 时间:2024/06/05 10:22

题意:调整数组顺序使得奇数位于偶数前面
思路:搞两个指针一前一后
代码:

package MianShiTi_14;public class MianShiTi_14 {    //将奇数都移到前面,偶数都移到后面    public static void EvenExchangeOdd(int[] num) throws Exception {        if(num == null || num.length <= 0){            throw new Exception("invalid array");        }        int begin = 0;        int end = num.length - 1;        while (begin < end) {            while (begin < end && (num[begin]& 0x1) !=0){                begin++;}            while (begin < end && (num[end] & 0x1) == 0){                end--;}            if(begin < end){            int tmp = num[begin];            num[begin] = num[end];            num[end] = tmp;            }        }    }    //将能被3整数的都移到后面,不能被3整除的移到前面。    public static void test3(int[] num) throws Exception {        if(num == null || num.length <= 0){            throw new Exception("invalid array");        }        int begin = 0;        int end = num.length - 1;        while (begin < end) {            while (begin < end && !is3dividedable(num[begin])){                begin++;}            while (begin < end && is3dividedable(num[end])){                end--;}            if(begin < end){            int tmp = num[begin];            num[begin] = num[end];            num[end] = tmp;            }        }    }    public static boolean is3dividedable(int number) {        return (number % 3 == 0)?true:false;    }    public static void prinrArray(int[] number) {        for (int i : number) {            System.out.print(i+" ");        }    }    public static void main(String[] args) throws Exception {        int[] num = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};        EvenExchangeOdd(num);        prinrArray(num);        System.out.println();        test3(num);        prinrArray(num);    }}   
0 0
原创粉丝点击