目录
LeetCode 739.每日温度
LeetCode 496.下一个更大元素!
LeetCode 739.每日温度
文章讲解:代码随想录
力扣题目:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
代码如下(Java):
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int lens = temperatures.length;
int[] res = new int[lens];
Deque<Integer> stack = new LinkedList<>();
stack.push(0);
for(int i = 1; i < lens; i++){
if(temperatures[i] <= temperatures[stack.peek()]){
stack.push(i);
}else{
while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]){
res[stack.peek()] = i - stack.peek();
stack.pop();
}
stack.push(i);
}
}
return res;
}
}
LeetCode 496.下一个更大元素!
文章讲解:代码随想录
力扣题目:LeetCode 496.下一个更大元素!
代码如下(Java):
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Stack<Integer> temp = new Stack<>();
int[] res = new int[nums1.length];
Arrays.fill(res,-1);
HashMap<Integer, Integer> hashMap = new HashMap<>();
for(int i = 0; i < nums1.length; i++) hashMap.put(nums1[i], i);
temp.add(0);
for(int i = 1; i < nums2.length; i++){
if(nums2[i] <= nums2[temp.peek()]){
temp.add(i);
}else{
while(!temp.isEmpty() && nums2[temp.peek()] < nums2[i]){
if(hashMap.containsKey(nums2[temp.peek()])){
Integer index = hashMap.get(nums2[temp.peek()]);
res[index] = nums2[i];
}
temp.pop();
}
temp.add(i);
}
}
return res;
}
}