题目
类型:数组
解题思路
使用指针 i 和 j 分别代表未处理区间的左右端点,当 nums[i] 不为偶数时,将 i 和 j 两个位置互换,原有位置 j 必然是奇数(已处理好),让 j 自减左移,但原有位置 i 交换后不确保是偶数,需要再次检查。
代码
class Solution {
public int[] sortArrayByParity(int[] nums) {
int n = nums.length;
for (int i = 0, j = n - 1; i < j; i++) {
if (nums[i] % 2 == 1) {
int c = nums[j];
nums[j--] = nums[i];
nums[i--] = c;
}
}
return nums;
}
}