LeetCode:739. 每日温度
739. 每日温度 - 力扣(LeetCode)
1.思路
自定义一个栈空间存储数组索引,将大于当前索引的数值时,计算索引差值,栈顶元素弹出,循环此步骤,直到:小于等于当前索引数值时,将当前索引加入栈中。
2.代码实现
// 超时
// 暴力解法:两层for循环,一层定义起始位置,一层定义终止位置。终止的情况有两种:一个是遇到大于当前节点的值,一个遍历到结尾没有遇到大于当前节点的值,使用一个局部变量和一个标识符标记即可
class Solution {public int[] dailyTemperatures(int[] temperatures) {int[] answer = new int[temperatures.length];for (int i = 0; i < temperatures.length; i++) {int res = 0;boolean flag = false;for (int j = i; j < temperatures.length; j++) {if (temperatures[j] > temperatures[i]) {answer[i] = res;flag = true;break;}res++;}if (!flag) {answer[i] = 0;}}return answer;}
}// 单调栈
class Solution {public int[] dailyTemperatures(int[] temperatures) {Stack<Integer> stack = new Stack<>(); // 存储数组索引stack.push(0);int[] res = new int[temperatures.length];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()]) {res[stack.peek()] = i - stack.peek();stack.pop();}stack.push(i); // 如果符合单调递增,则加入栈}}return res;}
}
3.复杂度分析
时间复杂度:O(n).
空间复杂度:O(n).
LeetCode:496.下一个更大元素 I
496. 下一个更大元素 I - 力扣(LeetCode)
1.思路
将数组1中的元素映射到map中,对数组2进行遍历构造单调栈,当前元素小于栈顶元素时,入栈即可。当前元素大于栈顶元素时进行判断栈顶元素是否存在map中,对其进行循环判断,如果存在则将当前元素加入到和数组1值相同的索引下的结果集中。
2.代码实现
// 单调栈
class Solution {public int[] nextGreaterElement(int[] nums1, int[] nums2) {Stack<Integer> stack = new Stack<>();int[] res = new int[nums1.length];Arrays.fill(res, -1);Map<Integer, Integer> map = new HashMap<>();for (int i = 0; i < nums1.length; i++) {map.put(nums1[i], i);}stack.add(0);for (int i = 1; i < nums2.length; i++) {if (nums2[i] <= stack.peek()) {stack.add(i);} else {while (!stack.isEmpty() && nums2[i] > nums2[stack.peek()]) {if (map.containsKey(nums2[stack.peek()])) {int idx = map.get(nums2[stack.peek()]);res[idx] = nums2[i]; }// stack.pop();}stack.add(i);}}return res;}
}// 暴力解法:ac
class Solution {public int[] nextGreaterElement(int[] nums1, int[] nums2) {int[] res = new int[nums1.length];for (int i = 0; i < nums1.length; i++) {res[i] = -1;}for (int i = 0; i < nums1.length; i++) {for (int j = 0; j < nums2.length; j++) {if (nums1[i] == nums2[j]) {for (int k = j + 1; k < nums2.length; k++) {if (nums2[k] > nums2[j]) {res[i] = nums2[k];break;}}break;}}}return res;}
}
3.复杂度分析
时间复杂度:O(n^2).
空间复杂度:O(n).