vault backup: 2022-07-27 11:24:56

This commit is contained in:
juan 2022-07-27 11:24:56 +08:00
parent 3c680b8971
commit 2ffb472c57

View file

@ -68,4 +68,36 @@ Stack is FILO, which means, when iterating from the last element, if you push a
### Solution
```cpp
```cpp
class Solution {
public:
vector<int> nextGreaterElement(vector<int> &nums1, vector<int> &nums2) {
// Hash table to link the subsets.
unordered_map<int, int> greater;
stack<int> 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<int> 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;
}
};
```