LeetCode 496. 下一个更大元素 I
原题链接
简单
作者:
我是java同学
,
2023-10-07 16:58:32
,
所有人可见
,
阅读 60
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size(), m = nums2.size();
vector<int> res(n);
stack<int> st;
unordered_map<int, int> hash;
for (int i = m - 1; i >= 0; i -- ) {
int x = nums2[i];
while (!st.empty() && st.top() <= x)
st.pop();
if (!st.empty()) hash[x] = st.top();
else hash[x] = -1;
st.push(nums2[i]);
}
for (int i = 0; i < n; i ++ ) res[i] = hash[nums1[i]];
return res;
}
};
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size(), m = nums2.size();
vector<int> res(n);
for (int i = 0; i < n; i ++ ) {
int x = nums1[i];
int minv = 0;
for (int j = 0; j < m; j ++ ) {
if (nums2[j] == x) {
while (true) {
while (j < m && nums[j] <= x) j ++ ;
if (j < m) res[i] = nums2[j];
else res[i] = -1;
break;
}
}
}
}
return res;
}
};