739.每日温度
解题思路:
维护一个单调栈,栈中存的是元素的下标,需要元素的值可以通过下标访问得到,遍历下标。通过栈更新数组的值。
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
Stack<Integer> stk = new Stack<>();
int[] ans = new int[temperatures.length];
Arrays.fill(ans, 0);
stk.push(0);
for (int i = 1; i < temperatures.length; i++) {
if(temperatures[i] < temperatures[stk.peek()]){ //小于栈里的内容
stk.push(i);
}else if(temperatures[i] == temperatures[stk.peek()]){
stk.push(i);
}else{ // 大于栈里的内容
// 开始弹出元素
while(!stk.empty() && temperatures[i] > temperatures[stk.peek()]){
ans[stk.peek()] = i - stk.peek();
stk.pop();
}
stk.push(i);
}
}
return ans;
}
}
简化代码:
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
Stack<Integer> stk = new Stack<>();
int[] ans = new int[temperatures.length];
Arrays.fill(ans, 0);
stk.push(0);
for (int i = 1; i < temperatures.length; i++) {
if(temperatures[i] > temperatures[stk.peek()]){
while(!stk.empty() && temperatures[i] > temperatures[stk.peek()]){
ans[stk.peek()] = i - stk.peek();
stk.pop();
}
}
stk.push(i);
}
return ans;
}
}
496.下一个更大元素I
题目链接:496. 下一个更大元素 I - 力扣(Leetcode)
解题思路:
这次记录结果是用一个map记录的,记录每一个元素的下一个更大的元素。
还有一个点就是,结果可以用复用nums1数组,不需要单独创建新数组。
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Stack<Integer> stk = new Stack<>();
stk.push(0);
// int[] rcd = new int[nums2.length];
HashMap<Integer,Integer> hashMap = new HashMap<>();
for(int i = 0; i < nums2.length; i++){
if(nums2[i] < nums2[stk.peek()]){
stk.push(i);
}else if(nums2[i] == nums2[stk.peek()]){
stk.push(i);
}else{
while(!stk.empty() && nums2[i] > nums2[stk.peek()]){
hashMap.put(nums2[stk.peek()], nums2[i]);
// rcd[stk,peek()] = nums2[i];
stk.pop();
}
stk.push(i);
}
}
while(!stk.empty()){
hashMap.put(nums2[stk.peek()], -1);
stk.pop();
}
for(int i = 0; i < nums1.length; i++){
nums1[i] = hashMap.get(nums1[i]);
}
return nums1;
}
}
简化写法:
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Stack<Integer> stk = new Stack<>();
stk.push(0);
// int[] rcd = new int[nums2.length];
HashMap<Integer,Integer> hashMap = new HashMap<>();
for(int i = 0; i < nums2.length; i++){
if(nums2[i] > nums2[stk.peek()]){
while(!stk.empty() && nums2[i] > nums2[stk.peek()]){
hashMap.put(nums2[stk.peek()], nums2[i]);
// rcd[stk,peek()] = nums2[i];
stk.pop();
}
}
stk.push(i);
}
while(!stk.empty()){
hashMap.put(nums2[stk.peek()], -1);
stk.pop();
}
for(int i = 0; i < nums1.length; i++){
nums1[i] = hashMap.get(nums1[i]);
}
return nums1;
}
}