每日一题-leetcode

调整数组顺序使奇数在偶数前

输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分

 

输入:nums = [1,2,3,4]
输出:[1,3,2,4] 
注:[3,1,2,4] 也是正确的答案之一

方法一:辅助数组

建立一个数组,以及两个头尾指针指向数组的头和尾,两指针一起移动,遇到奇数前指针遇到偶数放后指针
class Solution {
    public int[] exchange(int[] nums) {
        int temp[];
        int a = nums.length;
        temp = new int[a];
        int t1 = 0;
        int t2 = nums.length - 1; 
        for(int i:nums){
            if(i % 2 != 0){
                temp[t1] = i; 
                t1++;
            }else{
                temp[t2] = i;
                t2--;
            }
        }
        return temp;

    }
}

  方法二:双指针

初始化: i , j 双指针,分别指向数组 nums 左右两端;
循环交换: 当 i = j 时跳出;
指针 ii 遇到奇数则执行 i=i+1 跳过,直到找到偶数;
指针 jj 遇到偶数则执行 j=j−1 跳过,直到找到奇数;
交换 nums[i] 和 nums[j] 值;
返回值: 返回已修改的nums 数组。

class Solution {
    public int[] exchange(int[] nums) {
        int t1 = 0;
        int t2 = nums.length - 1;
        int temp = 0; 
        while(t1 < t2){
            while(t1 < t2 && (nums[t1] & 1) == 1) t1++;
            while(t1 < t2 && (nums[t2] & 1) == 0) t2--;
            temp = nums[t1];
            nums[t1] = nums[t2];
            nums[t2] = temp;
        }
    return nums;

    }
}

  

 

posted @ 2021-08-10 09:57  YBINing  阅读(116)  评论(0编辑  收藏  举报