今天开始了单调栈的学习,主要是找相邻的比当前大或小的元素。当单调栈里存放的元素递增,则是找向右的比当前位置大的元素,递减反之。
739. 每日温度
这个题目是典型的单调栈问题,就是需要找到大的元素的索引,减去当前元素的索引,然后存入数组中返回即可。
难点在于索引的控制,代码如下:
public int[] dailyTemperatures(int[] temperatures) {
int[] dp = new int[temperatures.length];
Stack<Integer> a = new Stack<>();
for(int i=0;i<temperatures.length;i++){
while(!a.isEmpty()&&temperatures[i]>temperatures[a.peek()]){
dp[a.peek()] = i-a.pop();
}
if(a.isEmpty()){
a.push(i);
continue;
}
if(!a.isEmpty()&&temperatures[i]<=temperatures[a.peek()]){
a.push(i);
}
}
return dp;
}
496. 下一个更大元素 I
你管这题叫tmd简单题,真的是恶心。、
首先建立映射关系,这边使用到的是hashMap来存储,key是值,value是索引,这里要返回的数组的长度是子集的长度,要遍历的是长数组,代码如下:
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] dp = new int[nums1.length];
Arrays.fill(dp,-1);
Stack<Integer> a = new Stack<>();
a.push(0);
Map<Integer,Integer> map = new HashMap();
for(int i=0;i<nums1.length;i++){
map.put(nums1[i],i);
}
for(int i=1;i<nums2.length;i++){
if(nums2[i]<=nums2[a.peek()]){
a.push(i);
}else{
while(!a.isEmpty()&&nums2[i]>nums2[a.peek()]){
if(map.containsKey(nums2[a.peek()])){
dp[map.get(nums2[a.peek()])] = nums2[i];
}
a.pop();
}
a.push(i);
}
}
return dp;
}