Sort Array By Parity

https://leetcode.com/explore/learn/card/fun-with-arrays/511/in-place-operations/3260/

2 pointer solution

只有当当前i是奇数,j是偶数是置换。否则,i 和 j相互靠近

class Solution:
    def sortArrayByParity(self, A: List[int]) -> List[int]:
        i= 0
        j = len(A)-1
        while i < j:
            if A[i] % 2 == 1 and A[j] % 2 == 0:
                A[j],A[i] = A[i],A[j]
            
            if A[i] % 2 == 0:
                i+=1
            
            if A[j] % 2 == 1:
                j-=1
        
        return A 

这道题的变形

Squares of Sorted Array

Brutal Force

Two Pointer

Last updated