The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
For number 2 in the first array, the next greater number for it in the second array is 3.
For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
Note:
All elements in nums1 and nums2 are unique.
The length of both nums1 and nums2 would not exceed 1000.
思路:
首先建立一下nums1中数字和index的映射,然后遍历nums2建立单调递减栈,这里储存的可以是nums2也可以是num本身。根据这个单调栈的性质,每一次遇到比栈顶更大的数字,开始pop,并且在nums1中查找这些数字,如果存在于nums1,通过hash找到坐标,将相应位置替换为nums2[i]。如果比栈顶小,说明栈内元素尚未遇到next greater,继续排队等待。新元素在排除掉之前比它小的所有栈顶元素后(while loop)入栈。
Time complexity: O(n), n is length of nums2。
Space complexity: O(n)。
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
vector<int> res(nums1.size(), -1);
unordered_map<int, int> hash;
stack<int> st;
for (int i = 0; i < nums1.size(); i++) hash[nums1[i]] = i;
for (int i = 0; i < nums2.size(); i++) {
while (!st.empty() && nums2[st.top()] < nums2[i]) {
int top = st.top(); st.pop();
if (hash.find(nums2[top]) == hash.end()) continue;
res[hash[nums2[top]]] = nums2[i];
}
st.push(i);
}
return res;
}
};
另一种写法,hashmap 用来保存num和next greater的映射,栈保存num2中的数字本身。
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
vector<int> res;
stack<int> st;
unordered_map<int, int> m;
for (int num : nums) {
while (!st.empty() && st.top() < num) {
m[st.top()] = num; st.pop();
}
st.push(num);
}
for (int num : findNums) {
res.push_back(m.count(num) ? m[num] : -1);
}
return res;
}
};