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

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


/**
 * 方法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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值