LeetCode 922. Sort Array By Parity II
考点 | 难度 |
---|---|
Sorting | Easy |
题目
Given an array of integers nums
, half of the integers in nums
are odd, and the other half are even.
Sort the array so that whenever nums[i]
is odd, i
is odd, and whenever nums[i]
is even, i
is even.
Return any answer array that satisfies this condition.
思路
找到第一个不在正确位置的奇数和偶数,swap。
答案
public int[] sortArrayByParityII(int[] A) {
int even = 0, odd = 1;
while(true){
while(even < A.length && A[even] % 2 == 0)
even += 2;
while(odd < A.length && A[odd] % 2 != 0)
odd += 2;
if(odd >= A.length || even >= A.length) return A;
int temp = A[even];
A[even] = A[odd];
A[odd] = temp;
}
}