题目

类型:数组

image.png

解题思路

使用指针 i 和 j 分别代表未处理区间的左右端点,当 nums[i] 不为偶数时,将 i 和 j 两个位置互换,原有位置 j 必然是奇数(已处理好),让 j 自减左移,但原有位置 i 交换后不确保是偶数,需要再次检查。

代码

  1. class Solution {
  2. public int[] sortArrayByParity(int[] nums) {
  3. int n = nums.length;
  4. for (int i = 0, j = n - 1; i < j; i++) {
  5. if (nums[i] % 2 == 1) {
  6. int c = nums[j];
  7. nums[j--] = nums[i];
  8. nums[i--] = c;
  9. }
  10. }
  11. return nums;
  12. }
  13. }