diff --git a/OJ notes/pages/Leetcode Next-Greater-Element-I.md b/OJ notes/pages/Leetcode Next-Greater-Element-I.md index 1c62aca..7644ee7 100644 --- a/OJ notes/pages/Leetcode Next-Greater-Element-I.md +++ b/OJ notes/pages/Leetcode Next-Greater-Element-I.md @@ -68,4 +68,36 @@ Stack is FILO, which means, when iterating from the last element, if you push a ### Solution -```cpp \ No newline at end of file +```cpp +class Solution { +public: + vector nextGreaterElement(vector &nums1, vector &nums2) { + // Hash table to link the subsets. + unordered_map greater; + stack st; + + for (int i = nums2.size() - 1; i >= 0; i--) { + while (!st.empty() && st.top() < nums2[i]) { + st.pop(); + } + if (!st.empty()) { + greater[nums2[i]] = st.top(); + } + + st.push(nums2[i]); + } + + // double pointers can't be used, because nums doesn't have a order. + vector ans(nums1.size()); + for (int i = 0, size1 = nums1.size(); i < size1; i++) { + if (greater.find(nums1[i]) != greater.end()) { + ans[i] = greater[nums1[i]]; + } else { + ans[i] = -1; + } + } + + return ans; + } +}; +``` \ No newline at end of file