面试题21:调整数组顺序是奇数位于偶数前面

题目

该系列文章题目和思路均参考自:《剑指Offer》- Page 129

 

解法

思路1:看到该问题,如果对快速排序的循环不变式比较熟悉的话,就很容易想到快速排序中的partition方法,其中就是对数组根据不同的条件进行划分的过程。

在快速排序中,三个指针将数组划分为三个区域,其中r指向数组最后一个元素,i初始指向数组开始的前一个元素,j指向数组中待排序的元素。因此它的循环不变式为:

  • array[start, i]为小于array[r]的元素
  • array[i+1, j-1]为大于array[r]的元素
  • array[j, r-1]为待排序的元素

类似的思路,将partition中的对元素条件的判断进行修改,即可改为解决此类问题的通用方法。

    /**
     * 思路1,仿照Partition算法的思想
     * @param array
     * @return
     */
    private static int[] reorderOddEvent(int[] array) {
        if (array == null || array.length == 0) {
            return null;
        }
        int i = -1;
        for (int j = 0; j < array.length; j++) {
            if (array[j] % 2 != 0) {
                i = i + 1;
                int temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
        return array;
    }

思路2:使用前后两个指针start和end,start从数组的开头进行遍历,直到指向第一个偶数,end从数组的结尾进行遍历直到指向第一个奇数,然后将两个指针指向的数组元素进行交换,完成后,start继续向后移动找到后一个偶数,end继续向前移动找到前一个奇数,继续交换,直到不满足start<end时,即将整个数组遍历完毕。

    /**
     * 思路2
     * @param array
     * @return
     */
    private static int[] reorderOddEvent_solution2(int[] array) {
        if (array == null || array.length == 0) {
            return null;
        }
        int start = 0;
        int end = array.length - 1;
        while (start < end) {
            // 移动start,直到指向偶数
            while (start < end && array[start] % 2 != 0) {
                start++;
            }
            // 移动end,直到指向奇数
            while (start < end && array[end] % 2 == 0) {
                end--;
            }
            // 交换两个位置上的元素
            if (start < end) {
                int temp = array[start];
                array[start] = array[end];
                array[end] = temp;
            }
        }
        return array;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值