[LeetCode] Next Greater Element I

496. Next Greater Element I

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
vector<int> st;
vector<int> greater(nums2.size(), -1);
unordered_map<int, int> lookup;
for(int i = nums2.size() - 1; i >= 0; i--) {
lookup[nums2[i]] = i;

while(!st.empty() and st.back() < nums2[i])
st.pop_back();
if(!st.empty())
greater[i] = st.back();

st.push_back(nums2[i]);
}

vector<int> res;
for(auto n : nums1) {
res.push_back(greater[lookup[n]]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/01/PS/LeetCode/next-greater-element-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.