leetcode 922.按奇偶排序数组II Java

做题博客链接

https://blog.youkuaiyun.com/qq_43349112/article/details/108542248

题目链接

https://leetcode-cn.com/problems/sort-array-by-parity-ii/

描述

给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。

对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。

你可以返回任何满足上述条件的数组作为答案。


提示:

2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000

示例

输入:[4,2,5,7]
输出:[4,5,2,7]
解释:[4,7,2,5][2,5,4,7][2,7,4,5] 也会被接受。

初始代码模板

class Solution {
    public int[] sortArrayByParityII(int[] nums) {
     
    }
}

代码

class Solution {
    public int[] sortArrayByParityII(int[] nums) {
        int i = 0;
        int j = 1;

        while (i < nums.length) {
            while (i < nums.length && (nums[i] & 1) == 0) {
                i += 2;
            }

            while (j < nums.length && (nums[j] & 1) == 1) {
                j += 2;
            }

            if (i < nums.length && j < nums.length) {
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
            }
        }

        return nums;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值