Steward
分享是一種喜悅、更是一種幸福
程式語言 - LeetCode - C++ - 496. Next Greater Element I
題目:

解答:
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int, int> mp;
stack<int> st;
vector<int> ans;
for (int x : nums2) {
while (!st.empty() && x > st.top()) {
mp[st.top()] = x;
st.pop();
}
st.push(x);
}
for (int x : nums1) {
if (mp.count(x)) {
ans.push_back(mp[x]);
}
else {
ans.push_back(-1);
}
}
return ans;
}
};