class Solution:
def sortArrayByParityII(self, A: List[int]) -> List[int]:
n=int(len(A)/2)
odd_index=[0]*n
even_index=[0]*n
count_odd=0
count_even=0
for i in range(0,len(A)):
a = A[i]%2
b = i%2
if a == 0 and b != 0:
odd_index[count_odd] = i
count_odd = count_odd+1
elif a != 0 and b == 0:
even_index[count_even] = i
count_even = count_even+1
for i in range(0,count_even):
c = A[odd_index[i]]
A[odd_index[i]] = A[even_index[i]]
A[even_index[i]]=c
return A
小周版
小周老师的思路是,以下标为0,1两个位置出发,步长为2,遍历列表,比如找到下标为奇值为偶时就让另一个位置出发找标偶值奇,再交换两个下标的位置就大功告成啦!速度比我的方法要快一点
class Solution:
def sortArrayByParityII(self, A: List[int]) -> List[int]:
jj=0
n = int(len(A)/2)
for i in range(0,n):
if A[2*i+1]%2 == 0:
for j in range(jj,n):
if A[2*j]%2 == 1:
jj=j
a=A[2*i+1]
A[2*i+1] = A[2*j]
A[2*j] = a
break
return A