Leetcode739. 每日温度
思路:暴力解法,时间超限
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
vector<int> result(temperatures.size());
for (int i = 0; i < temperatures.size(); i++){
for (int j = i + 1; j < temperatures.size(); j++){
if (temperatures[j] > temperatures[i]) {
result[i] = j - i;
break;
}
}
}
return result;
}
};
单调栈,空间换时间
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
vector<int> result(temperatures.size());
stack<int> st;
st.push(0);
for (int i = 0; i < temperatures.size(); i++){
if (temperatures[i] <= temperatures[st.top()]) st.push(i);
else {
while(!st.empty() && temperatures[i] > temperatures[st.top()]){
result[st.top()] = i - st.top();
st.pop();
}
st.push(i);
}
}
return result;
}
};
Leetcode496.下一个更大元素 I
文章链接:代码随想录
题目链接:496.下一个更大元素 I
思路:暴力解法
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
vector<int> result(nums1.size(), -1);
vector<int> tmp(nums1.size());
for(int i = 0; i < nums1.size(); i++){
for (int j = 0; j < nums2.size(); j++){
if (nums1[i] == nums2[j]){
tmp[i] = j;
// cout << tmp[i] << endl;
break;
}
}
}
for(int i = 0; i < tmp.size(); i++){
for (int j = tmp[i] + 1; j < nums2.size(); j++){
// cout << j << endl;
if (nums2[j] > nums2[tmp[i]]) {
result[i] = nums2[j];
break;
}
}
}
return result;
}
};
暴力解法,用umap作索引
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
vector<int> result(nums1.size(), -1);
unordered_map<int, int> umap;
for (int i = 0; i < nums1.size(); i++){
umap[nums1[i]] = i;
}
for (int i = 0; i < nums2.size(); i++){
if (umap.count(nums2[i]) == 0) continue;
for (int j = i; j < nums2.size(); j++){
if (nums2[j] > nums2[i]) {
result[umap[nums2[i]]] = nums2[j];
break;
}
}
}
return result;
}
};
单调栈,用map作索引,注意while循环的判断顺序,让是否未空先判断,避免超界运算
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
vector<int> result(nums1.size(), -1);
unordered_map<int, int> umap;
stack<int> st;
st.push(nums2[0]);
for (int i = 0; i < nums1.size(); i++){
umap[nums1[i]] = i;
}
for (int i = 1; i < nums2.size(); i++){
if (nums2[i] <= st.top()) st.push(nums2[i]);
else{
while (!st.empty() && nums2[i] > st.top() && umap.count(st.top()) > 0){
result[umap[st.top()]] = nums2[i];
st.pop();
}
st.push(nums2[i]);
}
}
return result;
}
};
第五十八天打卡,刚才老师叫去汇报课题进度,整的在家的人有点小慌,做题有点慢,加油!!!