剑指offer ----奇偶排序问题

it2025-04-27  8

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)

代码是全场最快内存最少的代码。其实思路很简单,走一边,将全部数据区分开来。 但是这里用了 from collections import deque。竟然可以import说明这是一个基本的知识。

deque

deque模块是python标准库collections中的一项,它提供了两端都可以操作的序列,这意味着,在序列的前后你都可以执行添加或删除操作。这很强大哎,之前用的list都是单边入单边出,也就是先入后出的结果。而这里可以两边出。具体如何操作呢?

输入输出东西

from collections import deque d=deque() d.appendleft(5) # 从左边加入 d.append(6) 从右边加入 d.appendleft(10) 从左边加入 d.append(100) 从右边加入 #d.appendright(100) #没有这个 a = list (d) 将deque转化为list 更好的操作 输出的 a = 10,5,6,100 b = d.pop() #b=100 从右边出来 c = d.popleft() #10 从左边出来
最新回复(0)