Given an array A
of non-negative integers, half of the integers in A are odd, and half of the integers are even.
Sort the array so that whenever A[i]
is odd, i
is odd; and whenever A[i]
is even, i
is even.
You may return any answer array that satisfies this condition.
两个指针,一个是奇一个是偶,for一遍数组,是奇数就放到奇数指针的位置,偶数就放到偶数指针位置。
class Solution(object): def sortArrayByParityII(self, A): """ :type A: List[int] :rtype: List[int] """ ans = [0] * len(A) even_index = 0 odd_index = 1 for value in A: if value % 2 == 0: ans[even_index] = value even_index += 2 else: ans[odd_index] = value odd_index += 2 return ans