Last active
August 29, 2015 14:03
-
-
Save monkerek/37e80cd7adc5db094774 to your computer and use it in GitHub Desktop.
3.3
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
# idea: use a 2-D array to mimic set of stacks. | |
# use a pivot index to indicate current stack that common pop() and push() are applyed to | |
# time complexity: O(1) | |
# space complexity: O(n) | |
class SetOfStack: | |
def __init__(self): | |
self.__stack = [] | |
self.__top = -1 | |
def pop(self): | |
if self.__top == -1: | |
print 'no element to pop' | |
return -1 | |
ret = self.__stack[self.__top].pop(-1) | |
if len(self.__stack[self.__top]) == 0: | |
self.__top -= 1 | |
return ret | |
def push(self, element): | |
STACK_LEN = 10 | |
if self.__top == -1 or len(self.__stack[self.__top]) == STACK_LEN: | |
self.__stack.append([]) | |
self.__top += 1 | |
self.__stack[self.__top].append(element) | |
def popAt(self, index): | |
if index < 0 or index > self.__top: | |
print 'invalid input' | |
return -1 | |
if len(self.__stack[index]) != 0: | |
return self.__stack[index].pop(-1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment