给你一个整数数组 nums,将 nums 中的的所有偶数元素移动到数组的前面,后跟所有奇数元素。返回满足此条件的 任一数组 作为答案。

方法一:遍历法

将数组进行两次遍历,首先遍历一次将偶数放在新数组中,在遍历一次将奇数依次放在数组里。

代码如下:

class Solution {
    public int[] sortArrayByParity(int[] nums) {
        int n = nums.length;
        int a = 0;
        int[] b = new int[n];
        for(int num :nums)
        {
            if(num % 2 == 0)
            {
                b[a++] = num; 
            }
        }
        for(int num:nums)
        {
            if(num % 2 == 1)
            {
                b[a++] = num;
            }
        }
        return b;
    }
}

方法二:双指针法

左指针从左到右遇到偶数遍历,右指针从右往左遇到奇数遍历。定义一个临时变量将左指针的数组赋予这个位置,再将右指针的数组赋予左指针的数组。从而达到前偶后奇的效果。

代码如下:

class Solution {
    public int[] sortArrayByParity(int[] nums) {
        int n = nums.length;
        int l = 0,r = n -1;
        while(l < r)
        {
            while(l < r && nums[l] % 2 == 0 )
            {
                l++;
            }
            while(l < r && nums[r] % 2 == 1)
            {
                r--;
            }
            if(l<r)
            {
                int temp = nums[l];
                nums[l]=nums[r];
                nums[r]=temp;
            }
        }
        return nums;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值