Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

leetcode 503.下一个更大元素 II #栈 #22

Open
webVueBlog opened this issue May 28, 2022 · 1 comment
Open

leetcode 503.下一个更大元素 II #栈 #22

webVueBlog opened this issue May 28, 2022 · 1 comment

Comments

@webVueBlog
Copy link
Member

image
503. 下一个更大元素 II

@webVueBlog
Copy link
Member Author

503. 下一个更大元素 II

/*
 * @lc app=leetcode.cn id=503 lang=javascript
 *
 * [503] 下一个更大元素 II
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @return {number[]}
 * 栈
[ 3, 2, 1, 4, 3, 2, 1, 4]
                          ?
[ 0, 1, 3, 7]
[ 4, 4, 4, -1]
[ 4, 4, 4, -1, -1, -1, -1, -1]
(80 ms)
 */
var nextGreaterElements = function(nums) {
    nums = nums.concat(nums);
    let len = nums.length;
    let oldLen = len / 2;
    let stack = [];
    let ans = new Array(oldLen).fill(-1);
    for (let i = 0; i < len; i++) {
        let current = nums[i]
        while (stack.length > 0 && current > nums[stack[stack.length - 1]]) {
            let topIndex = stack[stack.length - 1];
            ans[topIndex % oldLen] = current;
            stack.pop();
        }
        stack.push(i);
    }
    return ans;
};
// @lc code=end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant