所谓单调栈(Monotonic Stack)就是,栈里的元素是按单调递增或递减顺序排列的,它特别适用于解决查找一个序列中的一个元素的下一个更大的或更小的元素的问题。在前面的二叉搜索树系列题中就曾使用过单调递减栈。LeetCode 255. Verify Preorder Sequence in Binary Search Tree。
本系列将通过更多相关的题来熟练掌握单调栈的使用。
The next greater element of some element x
in an array is the first greater element that is to the right of x
in the same array.
You are given two distinct 0-indexed integer arrays nums1
and nums2
, where nums1
is a subset of nums2
.
For each 0 <= i < nums1.length
, find the index j
such that nums1[i] == nums2[j]
and determine the next greater element of nums2[j]
in nums2
. If there is no next greater element, then the answer for this query is -1
.
Return an array ans
of length nums1.length
such that ans[i]
is the next greater element as described above.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2] Output: [-1,3,-1] Explanation: The next greater element for each value of nums1 is as follows: - 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. - 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3. - 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.
Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4] Output: [3,-1] Explanation: The next greater element for each value of nums1 is as follows: - 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3. - 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.
Constraints:
1 <= nums1.length <= nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 104
- All integers in
nums1
andnums2
are unique. - All the integers of
nums1
also appear innums2
.
Follow up: Could you find an O(nums1.length + nums2.length)
solution?
题目先解释了一下什么是下一个更大数(next greater element), 就是对于数组的一个元素x,在x之后第一个比x大的那个元素。
题目给定两个数组nums1和nums2(数组里的数都是唯一的),nums1是nums2的子集,即nums1里的数全都来自nums2。现在要求找出nums1的每一个数在nums2中的下一个更大数(next greater element)。如不存在下一个最大数就为-1。
这是一道经典的单调栈的题,因为用暴力解法的话时间复杂度为O(n^2),而单调栈则为O(n)。基本解题思路就是使用单调栈求出nums2中所有数的下一个更大数,并用一个dict记录下每个数与其下一个更大数的关系,然后就可以直接得到nums1中所有数的下一个最大数。
定义一个堆栈要始终维持栈是单调递减的,遍历nums2,当栈为空或者当前数比栈顶的数小时,就把当前数压入栈;当遇到当前数比栈顶的数大时,就把栈中从栈顶开始所有比当前数小的数都弹出栈,当前数就是所有被弹出栈的数的下一个更大数,最后把当前数压入栈。遍历完nums2后,栈里面剩下的数都不存在下一个更大数。
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
st, nextGreater = [], {}
for num in nums2:
while st and st[-1] < num:
nextGreater[st.pop()] = num
st.append(num)
while st:
nextGreater[st.pop()] = -1
res = []
for num in nums1:
res.append(nextGreater[num])
return res