做题博客链接
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;
}
}