LeetCode刷题 Day59

90 阅读1分钟

LeetCode刷题 Day59

503. Next Greater Element II

Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.

The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.

Example 1:

Input: nums = [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2; 
The number 2 can't find next greater number. 
The second 1's next greater number needs to search circularly, which is also 2.

Example 2:

Input: nums = [1,2,3,4,3]
Output: [2,3,4,-1,4]

思路: 和Next Greater ElementI差不多思路,核心就是用stack + (stack.length - 1 && nums[i] > nums[stack[stack.length - 1]]) 判断

代码:

var nextGreaterElements = function(nums) {
    const len = nums.length;
    const res = Array(len).fill(-1);
    const stack = [];

    for (let i = 0; i < len * 2; i++) {
        while (stack.length && nums[i % len] > nums[stack[stack.length - 1]]) {
            let popIndex = stack.pop();
            res[popIndex] = nums[i % len];
        }

        stack.push(i % len);
    }

    return res;
};

时间复杂度: O(n) 空间复杂度: O(n)


42. Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Example 1:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.

Example 2:

Input: height = [4,2,0,3,2,5]
Output: 9

代码:

var trap = function(height) {
    let peakIdx = 0;
    let waterVol = 0;
    let leftBar = 0;
    let rightBar = height.length - 1;
    for (let i = 0; i < height.length; i++) {
        if (height[peakIdx] < height[i]) {
            peakIdx = i;
        }
    }
    // get left part volumn
    for (let i = 0; i < peakIdx; i++) {
        if (height[leftBar] < height[i]) {
            leftBar = i;
        } else {
            waterVol += (height[leftBar] - height[i]);
        }
    }
    // get right part volumn
    for (let i = height.length - 1; i > peakIdx; i--) {
        if (height[rightBar] < height[i]) {
            rightBar = i;
        } else {
            waterVol += (height[rightBar] - height[i]);
        }
    }
    return waterVol;
};

时间复杂度: O(n) 空间复杂度: O(1)