739. 每日温度

739. 每日温度 496.下一个更大元素 I 503. 下一个更大元素 II_数组


通常是一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置,此时我们就要想到可以用单调栈了。时间复杂度为O(n)。

单调栈结构类似这种:

739. 每日温度 496.下一个更大元素 I 503. 下一个更大元素 II_数据结构_02

class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int[] result = new int[temperatures.length];
LinkedList<Integer> list = new LinkedList<>();
list.addFirst(0);
for(int i = 1;i < temperatures.length;i++){
if(temperatures[i] <= temperatures[list.peek()]){
list.addFirst(i);
}else{
while(!list.isEmpty() && temperatures[i] > temperatures[list.peek()]){
result[list.peek()] = i - list.peek();
list.removeFirst();
}
list.addFirst(i);
}
}
return result;
}
}

739. 每日温度 496.下一个更大元素 I 503. 下一个更大元素 II_i++_03

496.下一个更大元素 I

739. 每日温度 496.下一个更大元素 I 503. 下一个更大元素 II_i++_04

class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
LinkedList<Integer> stack = new LinkedList<>();
Map<Integer,Integer> map = new HashMap<>();
int[] res = new int[nums1.length];
Arrays.fill(res,-1);
for(int i = 0;i < nums1.length;i++){
map.put(nums1[i],i);
}
stack.addFirst(0);
for(int i = 1;i < nums2.length;i++){
if(nums2[i] <= nums2[stack.peek()]){
stack.addFirst(i);
}else{
while(!stack.isEmpty() && nums2[i] > nums2[stack.peek()]){
if(map.containsKey(nums2[stack.peek()])){
res[map.get(nums2[stack.peek()])] = nums2[i];
}
stack.removeFirst();
}
stack.addFirst(i);
}
}
return res;
}
}

739. 每日温度 496.下一个更大元素 I 503. 下一个更大元素 II_数组_05

503. 下一个更大元素 II

739. 每日温度 496.下一个更大元素 I 503. 下一个更大元素 II_数据结构_06


nums数组再扩充一倍相同的num数组,然后再遍历取,最后保留前一半数组,可以采用取余方式来替代扩充数组。

class Solution {
public int[] nextGreaterElements(int[] nums) {
int[] result = new int[nums.length];
Arrays.fill(result,-1);
Stack<Integer> stack = new Stack<>();
stack.push(0);
for(int i = 0;i < nums.length * 2;i++){
if(nums[i % nums.length] <= nums[stack.peek()]){
stack.push(i % nums.length);
}else{
while(!stack.isEmpty() && nums[i % nums.length] > nums[stack.peek()]){
result[stack.peek()] = nums[i % nums.length];
stack.pop();
}
stack.push(i % nums.length);
}
}
return result;
}
}

739. 每日温度 496.下一个更大元素 I 503. 下一个更大元素 II_数组_07