922. Sort Array By Parity II

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public int[] sortArrayByParityII(int[] nums) {
int i = 0, j = 1;

while (i < nums.length - 1) {
if ((nums[i] & 1) == 1) {
// 偶数索引上存储了奇数,需要交换
while ((nums[j] & 1) == 1) {
// 奇数索引上存储的奇数则跳过
j += 2;
}
swap(nums, i, j);
}
i += 2;
}

return nums;
}

private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}

该题的双指针不同于其他题目中从两侧向中间靠近的双指针,而是一个指向偶数索引,一个指向奇数索引。注意题目说明了一半整数是奇数,一半整数是偶数,索引我们在移动奇数索引时无需判断指针是否会越界,因为一定会找到一个满足条件的偶数。

References

922. Sort Array By Parity II