class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: first = 0 last = len(A)-1 while first<last: m = A[first] n = A[last] if (m&1 is 1) and (n&1 is 0): A[first],A[last] = A[last],A[first] first += 1 last -= 1 elif m&1 is 0: first += 1 elif n&1 is 1: last -= 1 return A
88ms,13.9M
优化一:
class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: first = 0 last = len(A) for i in range(last): a = A[i] if a&1==0: first += 1 else: for j in range(last,first,-1): if A[j-1]&1==0: A[first],A[j-1] = A[j-1],A[first] last = j first += 1 break return A
80ms,14M