LeetCode刷题 Day58
739. Daily Temperatures
Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
Example 1:
Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Example 2:
Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
Example 3:
Input: temperatures = [30,60,90]
Output: [1,1,0]
思路:
- 用stack存储温度的index
- 当栈顶temperature[stack[stack.length - 1]]迎来更大值时,pop栈顶,然后用result记录result[i] = i - pop;
代码:
var dailyTemperatures = function(temperatures) {
let stack = [];
let res = Array(temperatures.length).fill(0);
for (let i = 0; i < temperatures.length; i++) {
while (stack.length > 0 && temperatures[stack[stack.length - 1]] < temperatures[i]) {
const top = stack.pop();
res[top] = i - top;
}
stack.push(i);
}
return res;
};
时间复杂度: O(n) 空间复杂度: O(n)
496. Next Greater Element I
The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.
You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.
For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.
Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
Output: [-1,3,-1]
Explanation: The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.
- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.
Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4]
Output: [3,-1]
Explanation: The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.
- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.
思路: 和上一题一样,不过要首先记录 {nums2[i]: first value greater than nums2[i] on the right handside} 键值对。 然后再遍历nums1 来获取最终结果
代码:
var nextGreaterElement = function(nums1, nums2) {
let stack = [];
let cache = {};
for (let i = 0; i < nums2.length; i++) {
while (stack.length > 0 && nums2[i] > nums2[stack[stack.length - 1]]) {
let pop = stack.pop();
cache[nums2[pop]] = nums2[i];
}
stack.push(i);
}
let res = Array(nums1.length).fill(0);
for(let i = 0; i < nums1.length; i++) {
res[i] = cache[nums1[i]] || -1;
}
return res;
};
时间复杂度: O(n) 空间复杂度: O(n)