How to compare integers in 2 stacks in O(n)?
I have two Stacks s1 and s2. s1 containing negative integers and s2 containing positive integers. Both Stacks have been sorted already from lowest value(at the bottom) to highest(at the top). x1 and x2 are integers in s1 and s2. I would like to check both Stacks to see wheth开发者_Python百科er [x1 + x2 = a given integer i]. What is the best way(or THE way) to do this in O(n)?
Update: x1 and x2 are integers..sorry
update 2: the method returns a boolean value and would have these parameters:
boolean method(Stack s1, Stack s2, int i)
method would return true if any integer x1 in s1 + any integer x2 in s2 = i
I assume you mean any number in s1 + any number in s2 is a given integer i.
If so,
- Pop off the top of both stacks
- Add them
- Do they equal i
- Yes --> you are done
- Is it greater than i?
- YES --> then, the negative number can have no counterpart, throw it away, pop off the next negative number from s1, goto 2
- NO --> then, the positive number can have no counterpart, throw it away, pop off the next positive number from s2, goto 2
(at any time, if a stack is empty, you are done -- there is no answer)
EDIT: I think I am wrong on step 4 based on your sort order -- but this basic idea should be close.
精彩评论