难度: Medium
原题连接
内容描述
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Note:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
思路 1 - 时间复杂度: O(N^2)- 空间复杂度: O(N)******
模拟push和pop
class Solution:
def validateStackSequences(self, pushed, popped):
"""
:type pushed: List[int]
:type popped: List[int]
:rtype: bool
"""
stack = []
for i in range(len(pushed)):
stack.append(pushed[i])
while stack and stack[-1] == popped[0]:
stack.pop()
popped = popped[1:]
return not stack
思路 2 - 时间复杂度: O(N)- 空间复杂度: O(N)******
模拟push和pop,但是可以用一个index来记录popped当前需要比较的位置,这样省去了每次列表移位的时间, beats 100%
class Solution:
def validateStackSequences(self, pushed, popped):
"""
:type pushed: List[int]
:type popped: List[int]
:rtype: bool
"""
i, stack = 0, []
for num in pushed:
stack.append(num)
while stack and stack[-1] == popped[i]:
stack.pop()
i += 1
return not stack