E-Dreamer

脚踏实地,仰望星空

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

PS:单调栈就是栈结构构成,不过元素进栈是按照一定的规则进栈,下面主要通过求数组下一个比其大的数每日温度这两个问题来讲述单调栈的使用。 

// 求数组中每个数的下一个比其大的数,如果没有返回-1

class Solution {
public: 
	vector<int> next_greater_element(vector<int> nums) {
		// 使用单调栈解决
		stack<int> sta; 
		vector<int> res(nums.size()); 
		for (int i = nums.size()-1; i >= 0; i--) {
			while (!sta.empty() && nums[i] >= sta.top()) {
				sta.pop(); 
			}
			res[i] = sta.empty() ? -1 : sta.top(); // 存入的是值
			sta.push(nums[i]); 
		}
		return res; 

	}
};


//每日温度

class Solution2  {
public:
	vector<int> daily_temperate(vector<int> nums) {
		// 跟上面类似
		stack<int> sta; 
		int n = nums.size(); 
		vector<int> res(n); 
		for (int i = n - 1; i >= 0; i--) {
			while (!sta.empty() && nums[i] >= sta.top()) {
				sta.pop();
			}
			res[i] = sta.empty() ? -1 : sta.top() - i;  // 注意这里是存入隔多少天后会有更高的温度
			sta.push(nums[i]); 
		}
		return res; 
	}
};

  

posted on 2020-02-29 22:23  E-Dreamer  阅读(222)  评论(0编辑  收藏  举报