739. 每日溫度
題目鏈接/文字講解:每日溫度
題設(shè):請(qǐng)根據(jù)每日 氣溫 列表鸟废,重新生成一個(gè)列表扫茅。對(duì)應(yīng)位置的輸出為:要想觀測(cè)到更高的氣溫,至少需要等待的天數(shù)。如果氣溫在這之后都不會(huì)升高及塘,請(qǐng)?jiān)谠撐恢糜?0 來代替。
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int lens=temperatures.length;
int []res=new int[lens];
Deque<Integer> stack=new LinkedList<>();
for(int i=0;i<lens;i++){
while(!stack.isEmpty()&&temperatures[i]>temperatures[stack.peek()]){
res[stack.peek()]=i-stack.peek();
stack.pop();
}
stack.push(i);
}
return res;
}
496.下一個(gè)更大元素 I
題目鏈接/文字講解:下一個(gè)更大元素 I
題設(shè):給你兩個(gè) 沒有重復(fù)元素 的數(shù)組 nums1 和 nums2 变隔,其中nums1 是 nums2 的子集懈叹。
請(qǐng)你找出 nums1 中每個(gè)元素在 nums2 中的下一個(gè)比其大的值。
nums1 中數(shù)字 x 的下一個(gè)更大元素是指 x 在 nums2 中對(duì)應(yīng)位置的右邊的第一個(gè)比 x 大的元素缤削。如果不存在窘哈,對(duì)應(yīng)位置輸出 -1 。
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums1.length; i++) {
map.put(nums1[i], i);
}
int[] res = new int[nums1.length];
Stack<Integer> stack = new Stack<>();
Arrays.fill(res, -1);
for (int i = 0; i < nums2.length; i++) {
while (!stack.isEmpty() && nums2[stack.peek()] < nums2[i]) {
int pre = nums2[stack.pop()];
if (map.containsKey(pre)) {
res[map.get(pre)] = nums2[i];
}
}
stack.push(i);
}
return res;
}
}