输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
#方法1:时间复杂度o(n) 空间复杂度o(n)
def oddevenorder(alist):
if not alist:
return None
if len(alist)==1:
return alist
odd=[]
even=[]
for i in alist:
if i % 2==1:
odd.append(i)
else:
even.append(i)
return odd+even
alist=[1,2,3,4]
oddevenorder(alist)
#方法2:o(n**2) 遇到偶数 先提出来,后面的往前挪动一位,偶数补到后面
def oddevenorder(alist):
if not alist:
return None
if len(alist)==1:
return alist
for i in alist:
if i %2 == 0:
alist.pop(alist.index(i))
alist.append(i)
return alist
alist=[1,2,3,4]
oddevenorder(alist)
#方法3:o(nlogn)
def oddevenorder(alist):
if not alist:
return None
if len(alist)==1:
return alist
left=0
right=len(alist)-1
while left<right:
while left<right and alist[left]%2!=0:
left += 1
while left<right and alist[right]%2==0:
right -= 1
tmp=alist[left]
alist[left]=alist[right]
alist[right]=tmp
return alist
alist=[1,-2,3,4]
oddevenorder(alist)
def oddevenorder(alist,func):
if not alist:
return None
if len(alist)==1:
return alist
left=0
right=len(alist)-1
while left<right:
# while left<right and alist[left]%2!=0:
while left<right and not func(alist[left]):
left += 1
while left<right and func(alist[right]):
right -= 1
tmp=alist[left]
alist[left]=alist[right]
alist[right]=tmp
return alist
def is_even(n):
#负数放在非负数前面
return n>=0
alist=[1,-2,3,4]
oddevenorder(alist,is_even)