题目描述
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
方法1:冒泡 O(N^2)
1 # -*- coding:utf-8 -*- 2 class Solution: 3 def reOrderArray(self, array): 4 def help(): 5 for i in range(len(array)): 6 if array[i]%2==1: 7 continue 8 j = i 9 while j < len(array)-1: 10 if array[j]%2 == 0 and array[j+1]%2!=0: 11 array[j],array[j+1]=array[j+1],array[j] 12 j+=1 13 help() 14 help() 15 return array
方法2:双端队列O(N)
1 # -*- coding:utf-8 -*- 2 from collections import deque 3 class Solution: 4 def reOrderArray(self, array): 5 d = deque() 6 for i in range(len(array)): 7 if array[i]%2==0: 8 d.append(array[i]) 9 if array[len(array)-i-1]%2==1: 10 d.appendleft(array[len(array)-i-1]) 11 return list(d)
2019-12-04 09:22:41