题目描述:
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
思路:
deque list-like container with fast appends and pops on either end
Operations on deque :
-
append() :- This function is used to insert the value in its argument to the right end of deque.
-
appendleft() :- This function is used to insert the value in its argument to the left end of deque.
-
pop() :- This function is used to delete an argument from the right end of deque.
-
popleft() :- This function is used to delete an argument from the left end of deque.
// An highlighted block
# Python code to demonstrate working of
# append(), appendleft(), pop(), and popleft()
# importing "collections" for deque operations
import collections
# initializing deque
de = collections.deque([1,2,3])
# using append() to insert element at right end
# inserts 4 at the end of deque
de.append(4)
# printing modified deque
print ("The deque after appending at right is : ")
print (de)
# using appendleft() to insert element at right end
# inserts 6 at the beginning of deque
de.appendleft(6)
# printing modified deque
print ("The deque after appending at left is : ")
print (de)
# using pop() to delete element from right end
# deletes 4 from the right end of deque
de.pop()
# printing modified deque
print ("The deque after deleting from right is : ")
print (de)
# using popleft() to delete element from left end
# deletes 6 from the left end of deque
de.popleft()
# printing modified deque
print ("The deque after deleting from left is : ")
print (de)
Output:
The deque after appending at right is :
deque([1, 2, 3, 4])
The deque after appending at left is :
deque([6, 1, 2, 3, 4])
The deque after deleting from right is :
deque([6, 1, 2, 3])
The deque after deleting from left is :
deque([1, 2, 3])
https://www.geeksforgeeks.org/deque-in-python/
Python实现:
// An highlighted block
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
lo = []
le = []
for d in array:
if d %2 == 1:
lo.append(d)
else:
le.append(d)
return lo+le
实现2:
// An highlighted block
from collections import deque
class Solution:
def reOrderArray(self, array):
# write code here
odd = deque()
x = len(array)
for i in range(x):
if array[x-i-1]%2 != 0:
odd.appendleft(array[x-i-1])
if array[i]%2 == 0:
odd.append(array[i])
return list(odd)