496 下一个更大元素 I

本文最后更新于:2022年4月9日 中午

给定两个 没有重复元素 的数组 nums1nums2 ,其中nums1nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。

nums1 中数字 x 的下一个更大元素是指 xnums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1 。

示例 1:

1
2
3
4
5
6
输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
输出: [-1,3,-1]
解释:
对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1
对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3
对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1

示例 2:

1
2
3
4
5
输入: nums1 = [2,4], nums2 = [1,2,3,4].
输出: [3,-1]
解释:
对于 num1 中的数字 2 ,第二个数组中的下一个较大数字是 3
对于 num1 中的数字 4 ,第二个数组中没有下一个更大的数字,因此输出 -1

提示:

  1. nums1nums2中所有元素是唯一的。
  2. nums1nums2 的数组大小都不超过1000。

Solution

参考:《算法小抄》3.7、**@AuroraRocks** 、@LeetCode官方

此题可以暴力求解,求出 num1 中每个数在 num2 中的位置,再从该位置往后找大于这个数的元素。时间复杂度 O(n^2^)

  • 单调栈
  • 利用数组模拟单调栈
1
2
3
4
5
6
7
8
9
10
11
12
# @lc code=start
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
if not nums1: return
ans = [-1 for _ in range(len(nums1))]
for i in range(len(nums1)-1, -1, -1):
s = nums2[nums2.index(nums1[i]):][::-1]
while s and nums1[i]>=s[-1]:
s.pop()
ans[i] = s[-1] if s else -1
return ans
# @lc code=end
  • 单调栈
  • 可以忽略数组 nums1,先对将 nums2 中的每一个元素,求出其下一个更大的元素。随后对于将这些答案放入哈希映射(HashMap)中,再遍历数组 nums1,并直接找出答案。

img

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
stack<int> stack;
unordered_map<int, int> umap;
for (int i = nums2.size() - 1; i >= 0; --i) {
while (!stack.empty() && nums2[i] >= stack.top())
stack.pop();
if (stack.empty()) {
umap[nums2[i]] = -1;
} else {
umap[nums2[i]] = stack.top();
}
stack.push(nums2[i]);
}
vector<int> res;
for (int num : nums1) {
res.push_back(umap[num]);
}
return res;
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!