算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 下一个更大元素 II,我们先来看题面:
https://leetcode-cn.com/problems/next-greater-element-ii/
Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums. The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.
给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素),输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。
输入: [1,2,1]
输出: [2,-1,2]
解释: 第一个 1 的下一个更大的数是 2;
数字 2 找不到下一个更大的数;
第二个 1 的下一个最大的数需要循环搜索,结果也是 2。
注意: 输入数组的长度不会超过 10000。
https://blog.csdn.net/weixin_44171872/article/details/107309751
方法1:使用单调栈
主要思路:
(1)对于循环数组,可以考虑这样理解:既将原数组扩展一倍,这样就相当于使用一个 2 倍长的数组表示出循环数组的效果;
(2)然后对这个两倍长的数组,直接使用单调栈从后向前找每个元素右侧的第一个大于其值的值,但只需要保存前一半即可;
(3)这样理解,也没必要实际的扩展数组,只需要对原数组遍历两遍即可;
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
vector<int>res(nums.size(),0);
stack<int> st;
//使用单调栈第一次遍历
for(int i=nums.size()-1;i>=0;--i){
while(!st.empty()&&st.top()<=nums[i]){
st.pop();
}
st.push(nums[i]);
}
//使用单调栈第二次遍历,保存相关的结果
for(int i=nums.size()-1;i>=0;--i){
while(!st.empty()&&st.top()<=nums[i]){
st.pop();
}
if(st.empty()){
res[i]=-1;
}
else{
res[i]=st.top();
}
st.push(nums[i]);
}
return res;
}
};
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: