通常是一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置,此时我们就要想到可以用单调栈了。时间复杂度为O(n)。
739. 每日温度
代码随想录
class Solution {public int[] dailyTemperatures(int[] temperatures) {Deque<Integer> stack=new LinkedList<>();int ans[] = new int[temperatures.length];stack.push(0);for (int i = 1; i < temperatures.length; i++) {if (temperatures[i] <= temperatures[stack.peek()]) {stack.push(i);} else {while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {ans[stack.peek()] = i - stack.peek();stack.pop();}stack.push(i);}}return ans;}
}
496.下一个更大元素 I
代码随想录
使用单调栈,首先要想单调栈是从大到小还是从小到大
class Solution {public int[] nextGreaterElement(int[] nums1, int[] nums2) {int ans[] = new int[nums1.length];Arrays.fill(ans, -1);Stack<Integer> stack = new Stack<>();stack.push(0);HashMap<Integer, Integer> map = new HashMap<>();for (int i = 0 ; i< nums1.length ; i++){map.put(nums1[i],i);}for (int i = 1; i < nums2.length; i++) {if (nums2[i] <= nums2[stack.peek()]) {stack.push(i);} else {while (!stack.isEmpty() && nums2[i] > nums2[stack.peek()]) {if (map.containsKey(nums2[stack.peek()])) {Integer index = map.get(nums2[stack.peek()]);ans[index] = nums2[i];}stack.pop();}stack.push(i);}}return ans;}
}