当前位置: 首页 > news >正文

代码随想录算法训练营第五十九天|503.下一个更大元素II、42. 接雨水

LeetCode 503 下一个更大元素II

题目链接:https://leetcode.cn/problems/next-greater-element-ii/

思路:

方法一:两个for循环遍历单调栈

第一个for循环确定数组中的某个值在右边有最大的数,第二个for循环是为了可以使数组变成循环数组
例子:[5,4,3,2,1]
1、栈里 4,3,2,1,0](右边为栈顶,栈内元素为下标)
2、从下标0开始再次循环
(模拟一次就目标了)

代码:

class Solution {
public:vector<int> nextGreaterElements(vector<int>& nums) {vector<int>result(nums.size(), -1);stack<int>st;st.push(0);for(int i = 1; i < nums.size(); i++){if(nums[i] <= nums[st.top()])st.push(i);else{while(!st.empty() && nums[i] > nums[st.top()]){result[st.top()] = nums[i];st.pop();}st.push(i);}}for(int i = 0; i < nums.size(); i++){if(nums[i] <= nums[st.top()])st.push(i);else{while(!st.empty() && nums[i] > nums[st.top()]){result[st.top()] = nums[i];st.pop();}st.push(i);}}return result;}
};

方法二:单调栈,用取模的方法对数组进行循环

代码

class Solution {
public:vector<int> nextGreaterElements(vector<int>& nums) {vector<int>result(nums.size(), -1);stack<int>st;st.push(0);for(int i = 1; i < nums.size() * 2; i++){if(nums[i % nums.size()] <= nums[st.top()])st.push(i % nums.size());else{while(!st.empty() && nums[i % nums.size()] > nums[st.top()]){result[st.top()] = nums[i % nums.size()];st.pop();}st.push(i % nums.size());}}return result;}
};

总结

关键在于如何循环数组


LeetCode 42 接雨水

题目链接:https://leetcode.cn/problems/trapping-rain-water/

思路:

本题关键点:

  1. 接雨水重点在于要找当前元素左边第一个比它的元素和右边第一个比它大的元素
  2. 接雨水是按行来计算的
    在这里插入图片描述
  3. 明确h和w是如何计算的,w在计算中必须还要减1

代码

class Solution {
public:int trap(vector<int>& height) {int result = 0;stack<int>st;st.push(0);for(int i = 1; i < height.size(); i++){if(height[i] <= height[st.top()])st.push(i);else{while(!st.empty() && height[i] > height[st.top()]){int mid = st.top();st.pop();if(!st.empty()){int h = min(height[i], height[st.top()]) - height[mid];int w = i - st.top() - 1;result += h * w;}}st.push(i);}}return result;}
};

总结

接雨水问题是经典问题,后续要多加练习


今日总结:

还有一天,加油!

http://www.lryc.cn/news/45583.html

相关文章:

  • 9、简单功能分析
  • 如何发送和接收参数?五种参数传递方法
  • 蓝桥杯C/C++VIP试题每日一练之矩形面积交
  • Spark大数据处理讲课笔记2.4 IDEA开发词频统计项目
  • 【ChatGPT 】国内无需注册 openai 即可访问 ChatGPT:ChatGPT Sidebar 浏览器扩展程序的安装与使用
  • 使用fetch()异步请求API数据实现汇率转换器
  • GPT-4“王炸”,10秒钟开发一套Web + APP 系统
  • Disjoint 集合数据结构或 Union-Find 算法简介
  • uniapp中nvue与vue的区别?
  • 带头双向循环链表的实现
  • 大屏使用dv-digital-flop定时刷新显示总人数
  • Java面向对象部分 个人学习记录
  • MySQL数据库——对Linux MySQL软件包的一些说明
  • 【JavaEE进阶】——第二节.Spring核心和设计思想
  • twitter开源算法(1)For You推荐系统架构
  • A General Framework for Uncertainty Estimation in Deep Learning源码阅读(二)
  • 串行通信协议---HART协议
  • 【独家】华为OD机试 - 寻找密码(C 语言解题)
  • FPGA有哪些优质的带源码的IP开源网站?
  • 基于模型预测控制(MPC)的微电网调度优化的研究(Matlab代码实现)
  • Postman接口测试之Mock快速入门
  • 分享一个国内可用的免费ChatGPT网站
  • 15. 三数之和(Java)
  • Navicat Premium 16安装教程
  • 蓝桥杯刷题冲刺 | 倒计时8天
  • 四.JAVA基础面试题:重要知识
  • 某面试官分享经验:看求职者第一眼,开口说第一句话,面试结果就差不多定了,准确率高达90%以上...
  • Java开发 - 消息队列之RabbitMQ初体验
  • 蓝桥杯入职项目(HTML + springBoot)
  • 【IAR工程】STM8S208RB基于ST标准库下按键检测