面试题21. 调整数组顺序使奇数位于偶数前面

题目

输入一个数组,实现一个函数来调整数组中数字的位置,使得所有奇数位于数组的前半部分,偶数位于数组的后半部分。
示例
输入:nums =
[1,2,3,4]
输出:[1,3,2,4]
注:[3,1,2,4]也是答案。
提示:1 <= nums.length <= 50000 1 <= nums[i] <= 10000

解题思路

三种方法,暴力解法,首尾双指针,快慢指针法。

第一种暴力解法,通过引入一个新的数组用于记录,从头开始遍历整个数组,奇数从新数组的开始为存入,偶数从最后一位开始存入,此方法时间和空间复杂度都是O(N),算法效率不是最优。

第二种首尾双指针法,算法过程:

  • 首先定义两个指针,分别指向数组头和数组尾;
  • 头指针向后循环,当遇到不是奇数时为止;尾指针向前循环,直到遇到偶数为止,并且头指针始终小于尾指针;
  • 此时头指针指向偶数,尾指针指向奇数,二者交换位置,
  • 继续下一次循环,直到首尾指针相遇。
    时间复杂度:O(N),空间复杂度:O(10).

第三种快慢指针法,顾名思义就是通过两个指针来实现,两个指针都从头开始往后,快指针往后找奇数,慢指针往后找偶数,当找到时就将二者交换,直到快指针到数组的最后位置为止。
时间复杂度:O(N),空间复杂度:O(10).

代码

class Solution {  
/************************ 暴力解法 ***************************/
    public int[] exchange(int[] nums) {
        if(nums == null || nums.length == 0 || nums.length == 1) return nums;
        int n = nums.length, a = 0,b = n-1;
        int[] newNums = new int[n];
        for(int i = 0;i<n;i++){
            if((nums[i]&1) == 1)
                newNums[a++] = nums[i];
            else
                newNums[b--] = nums[i];
        }
        return newNums;
    }

/************************ 首尾双指针 ***************************/
    public int[] exchange1(int[] nums) {
        if(nums == null || nums.length == 0 || nums.length == 1) return nums;
        int n = nums.length, i = 0,j = n-1;
        while(i < j){
            while((nums[i]&1) == 1 && i < j) i++; //左边的奇数跳过
            while((nums[j]&1) == 0 && i < j) j--; //右边的偶数跳过
            if(i < j) swap(nums,i,j);//此时i处为偶数,j处为奇数,二者交换
        }
        return nums;
    }
    public void swap(int[] nums,int i,int j){
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
/********************* 快慢指针法 ************************/
    public int[] exchange3(int[] nums) {
        if(nums == null || nums.length == 0 || nums.length == 1) return nums;
        int n = nums.length,fast = 0,low = 0;
        while(fast < n){
                if((nums[fast]&1 )== 1){
                    swap(nums,low,fast);
                    low++;
                }
                fast++;        
        }
        return nums;
    } 
}

变换
通过变换一下本题,改变题意:使得索引为奇数的元素在数组的前半部分,索引为偶数的在数组后面。算法还是类似,通过双指针实现。

/******** 奇数位的数(索引为奇数)在数组前面,偶数位的数(索引为偶数)在数组后面 *********/
    public int[] exchange2(int[] nums) {
        if(nums == null || nums.length == 0 || nums.length == 1) return nums;
        int n = nums.length, i = 1,j = n-1;
        if((n&1) == 0) j--;
        while(i < j){
            int tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
            i+=2;
            j-=2;
        }
        return nums;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值