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
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
nums =[val**2 for val in A]
nums.sort()
return nums
Two Pointer
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
i=0
j = len(A)-1
res = [0]*len(A)
idx = len(A)-1
while i <= j:
if A[i]**2 < A[j]**2:
res[idx]=A[j]**2
j-=1
idx-=1
else:
res[idx] =A[i]**2
i+=1
idx-=1
return res
Last updated
Was this helpful?