java官方文档中中建议使用deque来代替栈
单调递增栈
单调递减栈
单调栈模板
以从左到右遍历元素为例,介绍一下构造单调递增栈和单调递减栈的模板。
3.1 单调递增栈模板
def monotoneIncreasingStack(nums):
stack = []
for num in nums:
while stack and num >= stack[-1]:
stack.pop()
stack.append(num)
3.2 单调递减栈模板
def monotoneDecreasingStack(nums):
stack = []
for num in nums:
while stack and num <= stack[-1]:
stack.pop()
stack.append(num)
496. 下一个更大元素 I
nums1 中数字 x 的 下一个更大元素 是指 x 在 nums2 中对应位置 右侧 的 第一个 比 x 大的元素。
给你两个 没有重复元素 的数组 nums1 和 nums2 ,下标从 0 开始计数,其中nums1 是 nums2 的子集。
对于每个 0 <= i < nums1.length ,找出满足 nums1[i] == nums2[j] 的下标 j ,并且在 nums2 确定 nums2[j] 的 下一个更大元素 。如果不存在下一个更大元素,那么本次查询的答案是 -1 。
返回一个长度为 nums1.length 的数组 ans 作为答案,满足 ans[i] 是如上所述的 下一个更大元素 。
暴力法
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
int []res = new int[m];
for(int i=0;i<m;i++){
//外层循环遍历nums1数组
int j=0;
while(j<n&&nums2[j]!=nums1[i]){
++j;
//找出满足相等的下标
}
int k = j+1;
//确定nums2[j]的下一个更大元素
while(k<n&&nums2[k]<nums2[j]){
++k;
}
res[i]=k<n?nums2[k]:-1;
//存储答案
}
//返回答案
return res;
}
}
739. 每日温度
请根据每日 气温 列表 temperatures ,请计算在每一天需要等几天才会有更高的温度。如果气温在这之后都不会升高,请在该位置用 0 来代替。
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int len = temperatures.length;
int []res = new int[len];
for(int i=0;i<len;i++){
int j=i+1;
while(j<len&&temperatures[i]>=temperatures[j]){
j++;
}
res[i] = j<len?j-i:0;
}
return res;
}
}
316. 去除重复字母
给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
注意:该题与 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters 相同
需要使用「栈」作为辅助的数据结构;
需要记录每一个字符最后一次出现的下标;
判断当前读到的字母在栈中是否已经出现。
class Solution {
public String removeDuplicateLetters(String s) {
int len = s.length();
char [] charArray = s.toCharArray();
//convert String to charArray
int []lastIndex = new int[26];
//preserve the last index
for(int i=0;i<len;i++){
lastIndex[charArray[i]-'a']=i;
//preserve the last index of all the character
}
Deque<Character>st = new ArrayDeque<>();
//deque preserve the character
boolean []visited = new boolean[26];
for(int i=0;i<len;i++){
//visit all the character
if(visited[charArray[i]-'a']){
continue;
//if haven't visited
}
//if visited
while(!st.isEmpty() && (st.peekLast()>charArray[i]) &&( lastIndex[st.peekLast()-'a']>i)){
//if the stack isnot empty
// the last element of the stack larger than the present element (increase)
//if the last index of the character smaller than the index
//preserve the stack
Character top =st.removeLast();
//pop out the index
visited[top - 'a']=false;
//meiyou fangwenguo zhege yuansu
}
st.addLast(charArray[i]);
//add element
visited[charArray[i] - 'a'] = true;
}
StringBuilder stringBuilder = new StringBuilder();
for(char c:st){
stringBuilder.append(c);
}
return stringBuilder.toString();
}
}
引用资料
https://github.com/itcharge/LeetCode-Py/blob/main/Assets/Course/Course-Web-02.md
https://leetcode-cn.com/problemset/all/