Created
July 10, 2020 08:44
-
-
Save Just4test/db4093ff0411df673f0206354ce9710f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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