Skip to content

Instantly share code, notes, and snippets.

@Just4test
Created July 10, 2020 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Just4test/db4093ff0411df673f0206354ce9710f to your computer and use it in GitHub Desktop.
Save Just4test/db4093ff0411df673f0206354ce9710f to your computer and use it in GitHub Desktop.
from collections import deque #deque是一个实现了双端栈的list,popleft和appendleft。
def battle(bf, l=None, r=None):
# print('====================')
l = l or deque()
r = r or deque()
temp = deque()
i = 0
_len = len(bf)
bf.append(0)
while i < _len:
a = bf[i]
b = bf[i+1]
i += 1
if a > 0 and b < 0:
i += 1
if a > -b:
temp.append(a)
elif a < -b:
temp.append(b)
else:
temp.append(a)
bf = temp
# print(l,bf,r)
while bf and bf[0] < 0:
l.append(bf.popleft())
while bf and bf[-1] > 0:
r.appendleft(bf.pop())
# print(l,bf,r)
if bf:
return battle(bf, l, r)
else:
return list(l + r)
print('>>>>', battle([-1, -2, 3, -4, 5]))
print('>>>>', battle([-3,2,3,-1,-4]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment