Leetcode905:按奇偶排序数组

一、二次遍历+额外空间

解题思路
1、先创建一个数组result存放结果
2、第一次循环,先将偶数放进result
3、第二次循环,再将奇数跟在偶数后面

时间:1ms 空间42.1MB

代码

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


二、一次遍历+额外空间

解题思路
1、先创建一个数组result存放结果
2、循环,是偶数则放进result的前面,奇数则放在后面

时间:0ms 空间42.3MB

代码

class Solution {
    public int[] sortArrayByParity(int[] nums) {
        int[] result = new int[nums.length];
        int left = 0, right = nums.length - 1;
        for (int num : nums) {
            if (num % 2 == 0) {
                result[left++] = num;
            } else {
                result[right--] = num;
            }
        }
        return result;
    }
}


三、原地一次遍历

解题思路
1、双指针
2、前后同时判断是否为奇数或偶数

时间:1ms 空间:41.8MB

代码

class Solution {
    public int[] sortArrayByParity(int[] nums) {
        int i=0,j=nums.length-1;
        while(i<=j){
            //前奇后偶,交换
            if(nums[i]%2!=0&&nums[j]%2==0){
                int temp=nums[i];
                nums[i++] = nums[j];
                nums[j--] = temp;
            }
            //前偶后偶,前指针后移
            else if(nums[i]%2==0 && nums[j]%2==0){
                i++;
            }
            //前奇后奇,后指针前移
            else if(nums[i]%2!=0 && nums[j]%2!=0){
                j--;
            }
            //前偶后奇,不变
            else{
                i++;
                j--;
            }
        }
        return nums;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值