题意:
给定一个环形数组 nums, 对于每个元素e,找出e右边出现的第一个e',满足e‘ > e,若不存在e‘,令e’ 等于 1;
Example:
给定 nums = {1, 2, 1},返回 {2,-1, 2}
思路:
1. 从右向左利用栈保持一个升序数组 sta,若第 i 个元素与 sta 的头元素相比:
a. nums[i] >= sta.top(), sta循环弹出头元素,直到sta为空或 nums[i] < sta.top()。
b. nums[i] < sta.top(), 则显然 sta.top() 就是 e’, nums[i] 就是 e。
此时将nums[i] 入栈,保持sta为一个升序数组。
2. 显然第一步只能找到部分 e', 如 {1,2,1} 从右到左遍历时,第二个 '1' 此时不能找到 e'
注意到两点:
a. sta此时是一个升序数组
b.nums中此时未找到e’的元素组成一个非升序数组nums'
3. 继续从右向左遍历 nums', 在 sta 中找到 e'
代码:
时间复杂度 O(n), 空间复杂度 O (n)
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
vector<int> ret (nums.size(), -1);
vector<bool> isFound(nums.size(), false);
stack<int> sta;
for (int i = nums.size() - 1; i >= 0; --i){
while (!sta.empty() && sta.top() <= nums[i])
sta.pop();
if (!sta.empty()){
ret[i] = sta.top();
isFound[i] = true;
}
sta.push(nums[i]);
}
for (int i = nums.size() - 1; i >= 0; --i){
if (isFound[i] == false){
while (!sta.empty() && sta.top() <= nums[i])
sta.pop();
if (!sta.empty())
ret[i] = sta.top();
}
}
return ret;
}
};