leetcode菜鸡艰难刷题之路(每日温度)

最先想到的,暴力解法O(n*n)(大约击败5%)

class Solution 
{
public:
	vector<int> dailyTemperatures(vector<int>& T) 
	{
		vector<int> res;
		for (size_t i = 0; i < T.size(); i++)
		{
			int minValue = 0;
			for (size_t j = i+1; j < T.size(); j++)
			{
				if (T[i] < T[j])
				{
					minValue = j - i;
					break;
				}
			}
			res.push_back(minValue);
		}
		return res;
	}
};

优化
逆序使用单调栈(好像击败95%)
每当出现比栈中元素大的元素时,需要对栈中元素进行更新(即索引小且数值较大)

class Solution {
public:
	vector<int> dailyTemperatures(vector<int>& T) 
	{
		stack<int> s;
		int length = T.size();
		vector<int> res(length);
		for (int i = length - 1; i >= 0; i--)
		{
			while (!s.empty() && T[i] >= T[s.top()])
			{
				s.pop();
			}
			if (s.empty())
			{
				res[i] = 0;
			}
			else
			{
				res[i] = s.top() - i;
			}
			s.push(i);
		}
		return res;
	}
};

你可能感兴趣的:(leetcode菜鸡艰难刷题之路(每日温度))