739. 每日温度
题目链接:力扣
代码:
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int size = temperatures.size();
vector<int> result(size,0);
int count = 0;
for(int i = 0; i < size; i++)
{
count = 0;
for(int j = i; j < size; j++)
{
if(temperatures[j] <= temperatures[i])
count++;
else{
result[i] = count;
break;
}
}
}
return result;
}
};
超出时间限制
代码(单调栈):
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
vector<int> result(temperatures.size(),0);
stack<int> stk;
int cur;
for(int i = 0; i < temperatures.size(); i++)
{
if(stk.empty())
{
stk.push(i);
}else
{
while(!stk.empty())
{
cur = stk.top();
if(temperatures[cur] < temperatures[i])
{
stk.pop();
result[cur] = i - cur;
}else break;
}
stk.push(i);
}
}
return result;
}
};
好聪明的想法!时间复杂度和空间复杂度都是O(n)
496.下一个更大元素 I
题目链接:力扣
代码:
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
vector<int> result(nums1.size(),-1);
stack<int> stk;
int cur;
if(nums1.size() == 0)
return result;
unordered_map<int,int> umap;
for(int i = 0; i < nums1.size(); i++)
{
umap[nums1[i]] = i;
}
stk.push(0);
for(int i = 1; i < nums2.size(); i++)
{
if(nums2[i] <= nums2[stk.top()])
stk.push(i);
else
{
while(!stk.empty() && nums2[i] > nums2[stk.top()])
{
cur = stk.top();
if(umap.find(nums2[cur])!= umap.end())
{
int index = umap[nums2[cur]];
result[index] = nums2[i];
}
stk.pop();
}
stk.push(i);
}
}
return result;
}
};
因为不会重复 所以用map把nums1的存储起来 然后给nums2排序 然后找在nums1里是否存在