LeetCode:739. 每日温度 - 力扣(LeetCode)
1.思路
方法一:两层for循环,外层做定位,内层做比较,符合条件的赋值操作。暴力不给过... 方法二:单调栈法。用队列Deque维持一个单调栈。若当前索引下的数值小于栈顶元素对应的数值时存入当前数组索引下标。若当前索引下的数值大于栈顶索引下的数值时,将两者之差存入结果集中,同时弹出栈顶元素,这个过程循环进行。当前元素比完之后,将对应的索引下标加入栈中。
2.代码实现
// 暴力解法
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int[] answer = new int[temperatures.length];
for (int i = 0; i < temperatures.length; i++) {
for (int j = i + 1; j < temperatures.length; j++) {
if (temperatures[j] > temperatures[i]) {
answer[i] = j - i;
break;
}
}
}
return answer;
}
}
// 单调栈
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int[] result = new int[temperatures.length];
Deque<Integer> stack = new LinkedList<>(); // 单调栈,单调递增
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()]) {
result[stack.peek()] = i - stack.peek();
stack.pop();
}
}
stack.push(i); // 比完之后将较大值加入结果集中
}
return result;
}
}
3.复杂度分析
时间复杂度:O(n).
空间复杂度:O(n).
LeetCode:496. 下一个更大元素 I - 力扣(LeetCode)
1.思路
方法一:暴力解法躺了躺了 方法二:单调栈
2.代码实现
// 暴力解法清晰见底
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] ans = new int[nums1.length];
Arrays.fill(ans, -1);
// Deque<Integer> stack = new LinkedList<>();
// stack.push(0);
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]) {
ans[i] = nums2[k];
break;
}
}
}
}
}
return ans;
}
}
// 单调栈,掉头发
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] ans = new int[nums1.length];
Arrays.fill(ans, -1);
Deque<Integer> stack = new LinkedList<>();
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums1.length; i++) {
map.put(nums1[i], i); // 存nums1 方便遍历nums2时做对应值的查找
}
// 对nums2[]构建单调栈
stack.push(0);
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()]) {
// 用map判断nums1[]是否存在相同的元素,存在则获取该数值在nums1[]中的索引,将nums2[i]加入到ans[index]中
if (map.containsKey(nums2[stack.peek()])) {
int index = map.get(nums2[stack.peek()]);
ans[index] = nums2[i];
}
stack.pop(); // 每操作一个元素,弹出一个
}
stack.push(i); // 循环判断直到nums2[i] <= nums2[stack.peek()]为止
}
}
return ans;
}
}
3.复杂度分析
时间复杂度:O(n * m).
空间复杂度:O(n).