题目描述:
给定一个非负整数数组 A,返回一个数组,在该数组中, A 的所有偶数元素之后跟着所有奇数元素。
解法一:头尾指针,向中间走
class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: if not A: return i,j = 0,len(A)-1 while i<=j: while i<len(A) and A[i]%2 == 0 : i += 1 while j>=0 and A[j]%2 == 1 : j -= 1 if i>=len(A) or j<0 or i>j: break A[i],A[j] = A[j], A[i] i += 1 j -= 1 return A
解法二:
class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: return sorted(A, key = lambda x : x % 2)